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

sri*_*tsa 27 xml xslt xpath

在运行时,我可以有两种格式的XML文件:

  1. <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>  
        </diagram> 
    </root>
    
    Run Code Online (Sandbox Code Playgroud)
  2. <root>
        <diagram> 
            <graph>    
                <xaxis>1 2 3 12 312 3123 1231 23 </xaxis>
                <yaxis>1 2 3 12 312 3123 1231 23 </yaxis>
            </graph>  
        </diagram> 
    </root>
    
    Run Code Online (Sandbox Code Playgroud)

根据颜色属性的存在,我必须处理xaxis和yaxis的值.

我需要使用XSL来做到这一点.任何人都可以帮我暗示我可以检查这些条件的片段.

我试过用

<xsl: when test="graph[1]/@color">
     //some processing here using graph[1]/@color values
</xsl:when>
Run Code Online (Sandbox Code Playgroud)

我收到了一个错误......

Dim*_*hev 32

这是使用XSLT模式匹配和完全"推"样式的全部功能进行条件处理的一种非常简单的方法,这甚至避免了使用条件指令,例如:<xsl:if><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>
Run Code Online (Sandbox Code Playgroud)

当此转换应用于以下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>
Run Code Online (Sandbox Code Playgroud)

产生了想要的正确结果:

  Graph[1] has color
Run Code Online (Sandbox Code Playgroud)

当对此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>
Run Code Online (Sandbox Code Playgroud)

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

  Graph[1] has not color
Run Code Online (Sandbox Code Playgroud)

可以自定义此解决方案,并在第一个模板中放置必要的代码,如果需要,在第二个模板内.


vig*_*esh 17

像这样在一个匹配中自定义模板

<xsl:template match="diagram/graph">
  <xsl:choose>
    <xsl:when test="@color">
         Do the Task
    </xsl:when>
    <xsl:otherwise>
         Do the Task
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>**
Run Code Online (Sandbox Code Playgroud)


ann*_*ata 1

我不明白 - 除了使用 apply-templates 进行一些轻微的语法调整之外:

<xsl:template match="graph[1][@color]">
  <!-- your processing here -->
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

如果不知道您真正想做什么,我们无能为力。