且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 XSL 检查 XML 文件中是否存在属性

更新时间:2023-11-25 12:09:46

这里有一种非常简单的方法来进行条件处理,使用 XSLT 模式匹配的全部功能和专门的推送"样式,以及这甚至避免了使用条件指令的需要,例如 :

Here is a very simple way to do conditional processing using the full power of XSLT pattern matching and exclusively "push" style, and this even avoids the need to use conditional instructions such as <xsl:if> or <xsl:choose>:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/root/diagram[graph[1]/@color]">
  Graph[1] has color
 </xsl:template>

 <xsl:template match="/root/diagram[not(graph[1]/@color)]">
  Graph[1] has not color
 </xsl:template>
</xsl:stylesheet>

当此转换应用于以下 XML 文档时:

<root>
    <diagram>
        <graph color= "#ff00ff">
            <xaxis>1 2 3 12 312 3123 1231 23 </xaxis>
            <yaxis>1 2 3 12 312 3123 1231 23 </yaxis>
        </graph>
        <graph>
            <xaxis>101 102 103 1012 10312 103123 101231 1023 </xaxis>
            <yaxis>101 102 103 1012 10312 103123 101231 1023 </yaxis>
        </graph>
    </diagram>
</root>

产生想要的、正确的结果:

  Graph[1] has color

在此 XML 文档上应用相同的转换时:

<root>
    <diagram>
        <graph>
            <xaxis>101 102 103 1012 10312 103123 101231 1023 </xaxis>
            <yaxis>101 102 103 1012 10312 103123 101231 1023 </yaxis>
        </graph>
        <graph color= "#ff00ff">
            <xaxis>1 2 3 12 312 3123 1231 23 </xaxis>
            <yaxis>1 2 3 12 312 3123 1231 23 </yaxis>
        </graph>
    </diagram>
</root>

再次产生想要的正确结果:

  Graph[1] has not color

您可以自定义此解决方案并将任何必要的代码放入第一个模板中,如有必要,放入第二个模板中.

One can customize this solution and put whatever code is necessary inside the first template and if necessary, inside the second template.