1

xml ファイル内の特定のノードを見つける必要があります。<example>Some text</example>

次に、このノードとそのサブ要素をxmlファイルから抽出し、それを新しいxmlファイルに書き込みます。次に、元のxmlファイルから抽出されたノードを差し引いた残りのxmlノードを抽出した後、新しいxmlファイルに抽出する必要があります。ノード。

xslt または xpath でこれを行うにはどうすればよいですか?

4

1 に答える 1

2

特定のノードとそのサブツリーを除いたすべてのノードを出力する方法は次のとおりです。

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

     <xsl:template match="node()|@*">
      <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
     </xsl:template>

     <xsl:template match="example[. = 'Some text']"/>
</xsl:stylesheet>

この変換が次の XML ドキュメントに適用された場合(何も提供されていません!):

<a>
            <example>Some different text</example>
    <b>
        <c>
            <example>Some text</example>
        </c>
            <example>Some other text</example>
    </b>
</a>

必要な正しい結果が生成されます。

<a>
    <b>
        <c></c>
    </b>
</a>

必要なノードとそのサブツリーのみを抽出する方法は次のとおりです。

<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="example[. = 'Some text']">
  <xsl:copy-of select="."/>
 </xsl:template>

 <xsl:template match="text()"/>
</xsl:stylesheet>

同じ XML ドキュメント (上記) に適用すると、結果は次のようになります。

<example>Some text</example>

1 回の XSLT 1.0 変換で 2 つの異なる結果ドキュメントを作成することはできません

以下は、最初の結果を出力し、2 番目の結果をファイルに書き込む XSLT 2.0 変換です

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

 <xsl:variable name="vResult2">
  <xsl:apply-templates mode="result2"/>
 </xsl:variable>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="example[. = 'Some text']"/>

 <xsl:template match="/">
  <xsl:apply-templates/>

  <xsl:result-document href="file:///c:/temp/delete/result2.xml">
   <xsl:sequence select="$vResult2"/>
  </xsl:result-document>
 </xsl:template>

 <xsl:template mode="result2" match="example[. = 'Some text']">
  <xsl:copy-of select="."/>
 </xsl:template>

 <xsl:template mode="result2" match="text()"/>
</xsl:stylesheet>
于 2012-01-29T21:08:33.380 に答える