xlst处理时命名空间带来的小坑

Posted on 2025-05-13 18:42  云起  阅读(6)  评论(0)    收藏  举报

在处理xml的过程中,之前使用的转换脚本,没有获得预期的结果。
xml的节点结构没有问题,经过对比和排查发现,异常的xml文件中,节点中指定了命名空间。

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- 模板匹配根节点 -->
    <xsl:template match="/">
        <buttons_with_id>
            <!-- 匹配所有有id属性的button节点 -->
            <xsl:for-each select="//button[@id]">
                <xsl:copy-of select="."/>
            </xsl:for-each>
        </buttons_with_id>
    </xsl:template>
</xsl:stylesheet>
<!-- 正常的 -->
<interface>
    <group>
        <button id="btn1">Button 1</button>
    </group>
    <button>Unnamed Button</button>
    <button id="btn2">Button 2</button>
</interface>
<!-- 带命名空间 -->
<interface xmlns="test">
    <group>
        <button id="btn1">Button 1</button>
    </group>
    <button>Unnamed Button</button>
    <button id="btn2">Button 2</button>
</interface>

之前的xlst没有指定命名空间,会采用默认的空命名空间进行匹配,导致命名空间不一致,从而没有匹配到节点。
所以需要声明并指定命名空间,来进行匹配。

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:test="test">
    <!-- 模板匹配根节点 -->
    <xsl:template match="/">
        <buttons_with_id>
            <!-- 匹配所有有id属性的button节点 -->
            <xsl:for-each select="//test:button[@id]">
                <xsl:copy-of select="."/>
            </xsl:for-each>
        </buttons_with_id>
    </xsl:template>
</xsl:stylesheet>

如果需要匹配多个命名空间,可以使用或来适配。

xmlns:test1="test1"
xmlns:test2="test2"
<xsl:for-each select="//test1:button[@id] | //test2:button[@id]">

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3