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

XSLT转换XML为CSV时如何匹配同名嵌套Rule元素

XSLT转换嵌套Rule节点生成CSV格式输出方案

实现逻辑

  • 遍历所有type="per-file"的dataroot下的File节点,提取@path属性作为第一列值
  • 在每个File节点下定位type="rules"的tree节点,再筛选出name="MISRA_C"的RuleGroup节点
  • 匹配该RuleGroup下所有嵌套的Rule节点,筛选@id属性符合[1-9]+\.[1-9]+\.[1-9]+三段数字格式的节点,提取@id作为第二列值
  • 取符合条件的Rule节点下直接子节点Message的@severity、@text属性作为第三、第四列值
  • 各列之间用|拼接,每行对应一条输出记录

XSLT 2.0 实现代码

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="UTF-8" omit-xml-declaration="yes"/>
    <xsl:template match="/">
        <!-- 遍历所有文件节点 -->
        <xsl:for-each select="AnalysisData/dataroot[@type='per-file']/File">
            <xsl:variable name="filePath" select="@path"/>
            <!-- 筛选MISRA_C分组下符合id格式的Rule节点 -->
            <xsl:for-each select="tree[@type='rules']/RuleGroup[@name='MISRA_C']//Rule[matches(@id, '^[0-9]+\.[0-9]+\.[0-9]+$')]">
                <xsl:value-of select="concat('File@path=&quot;', $filePath, '&quot; | Rule@id=&quot;', @id, '&quot; | Message@severity=&quot;', Message/@severity, '&quot; | Message@text=&quot;', Message/@text, '&quot;')"/>
                <xsl:text>&#xa;</xsl:text>
            </xsl:for-each>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

XSLT 1.0 兼容适配方案

若运行环境仅支持XSLT 1.0,无内置正则匹配函数,可替换Rule节点筛选条件,通过字符串特征判断:

//Rule[
    contains(@id, '.') 
    and string-length(substring-before(@id, '.')) > 0 
    and contains(substring-after(@id, '.'), '.') 
    and string-length(substring-after(substring-after(@id, '.'), '.')) > 0 
    and not(contains(substring-after(substring-after(@id, '.'), '.'), '.'))
]

该条件可精准筛选id为三段且仅含两个分隔点的Rule节点,匹配需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:18:03