You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将gcovr XML格式代码覆盖率报告转换为JSON格式?

将gcovr XML覆盖率报告转换为JSON的方法

方法一:直接用gcovr生成JSON(最简便)

没必要先生成XML再转换,直接修改你的CMake目标对应的gcovr命令,让它直接输出JSON格式:

gcovr --json coverage.json -r ./build.Debug/

对应到CMake的setup_target_for_coverage_gcovr_xml配置,只需要把生成XML的参数替换成--json coverage.json即可,一步到位生成JSON格式的覆盖率报告。

方法二:Python脚本转换已有XML文件

如果已经有了生成好的coverage.xml,可以写个简单的Python脚本解析XML并转成JSON:

import xml.etree.ElementTree as ET
import json

# 解析XML文件
tree = ET.parse('coverage.xml')
root = tree.getroot()

# 构建JSON结构
coverage_result = {
    "overall_line_rate": float(root.attrib['line-rate']),
    "files": []
}

# 遍历XML中的包、类和行信息
for package in root.findall('packages/package'):
    for class_node in package.findall('classes/class'):
        file_info = {
            "filename": class_node.attrib['filename'],
            "line_rate": float(class_node.attrib['line-rate']),
            "covered_lines": []
        }
        for line in class_node.findall('lines/line'):
            file_info["covered_lines"].append({
                "line_number": int(line.attrib['number']),
                "hit_count": int(line.attrib['hits'])
            })
        coverage_result["files"].append(file_info)

# 写入JSON文件
with open('coverage.json', 'w', encoding='utf-8') as f:
    json.dump(coverage_result, f, indent=2)

运行脚本:

python convert_coverage.py

方法三:使用第三方转换工具

可以用covtojson工具来完成转换,安装后直接执行命令:

covtojson -i coverage.xml -o coverage.json

注:covtojson可通过pip安装。

内容的提问来源于stack exchange,提问作者JamesThomasMoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 11:59:51