簡體   English   中英

如何使用XSL檢查XML文件中是否存在屬性

[英]How to check if an attribute exists in a XML file using XSL

在運行時,我可以有兩種格式的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> 
  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> 

根據顏色屬性的存在,我必須處理xaxis和yaxis的值。

我需要使用XSL來做到這一點。 任何人都可以幫我暗示我可以檢查這些條件的片段。

我試過用

<xsl: when test="graph[1]/@color">
     //some processing here using graph[1]/@color values
</xsl:when>

我收到了一個錯誤......

這是使用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>

當此轉換應用於以下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

可以自定義此解決方案,並在第一個模板中放置必要的代碼,如果需要,在第二個模板內。

像這樣在一個匹配中自定義模板

<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>**
<xsl:when test="graph[1]/@color">
     //some processing here using graph[1]/@color values
</xsl:when>

我將在這里猜測,因為你的問題缺少許多重要信息,例如<xsl:when...出現的上下文。 如果你的評論是正確的,你想要做的是處理graph[1]/xaxis.../yaxis graph[1]/xaxis ,而不是graph[1]/@color值。

我不明白 - 除了使用apply-templates的一些輕微的語法調整:

<xsl:template match="graph[1][@color]">
  <!-- your processing here -->
</xsl:template>

在不知道你真正想做什么的情況下,我們無法告訴你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM