XSL を使用して XML ファイルに属性が存在するかどうかを確認する方法 質問する

XSL を使用して XML ファイルに属性が存在するかどうかを確認する方法 質問する

実行時には、2 つの形式の 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>
    

色属性の存在に応じて、x 軸と y 軸の値を処理する必要があります。

XSL を使用してこれを実行する必要があります。これらの条件を確認できるスニペットを教えていただける方はいらっしゃいますか。

使ってみた

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

エラーが発生しました...

ベストアンサー1

条件付き処理を実行する非常に簡単な方法は次のとおりです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

このソリューションはカスタマイズ可能必要なコードを最初のテンプレート内に配置し、必要に応じて 2 番目のテンプレート内にも配置します。

おすすめ記事