1

file1.xml

<config>
 <state version="10">
  <root value="100" group="5">
     <leaf number = "2"/>
  </root>
  <action value="2" step="4">
     <get score = "5"/>
  </action>
 </state>
</config>

file2.xml

<config>
 <state version="10">
  <root value="100" group="5">
     <leaf number = "6"/>
  </root>
  <parent>
      <child node="yes"/>
  </parent>
 </state>
</config>

output.xml

<config>
 <state version="10">
  <root value="100" group="5">
     <leaf number = "2"/>
     <leaf number = "6"/>
  </root>
  <action value="2" step="4">
     <get score = "5"/>
  </action>
  <parent>
      <child node="yes"/>
  </parent>
 </state>
</config>

これは、 XSLT を使用して属性値に基づいて 2 つの XML ファイルをマージしますか?のフォローアップの質問です。

各 XML ファイルに 2 つの異なるタグ (file1.xml のアクション タグと file2.xml の親タグ) があり、共通タグ () がトラバースされた後、出力ファイルに両方を表示する必要があります。

これらのタグが両方とも出力に反映されるように、XSLT を作成するのを手伝ってください。

4

1 に答える 1

0

JLRishie の良い答えを見ると、一致するルート要素をコピーする次のテンプレートが与えられます。

<xsl:template match="root">
   <xsl:copy>
    <xsl:apply-templates select="@* | node()" />
    <xsl:copy-of
      select="document('file2.xml')
          /config/state[@version = current()/../@version]
                 /root[@value = current()/@value and
                       @group = current()/@group]/*" />

  </xsl:copy>
</xsl:template>

これを拡張して file2.xml から非ルート要素を取得するには、file1.xml の状態要素と一致する新しいテンプレートを追加してから、file2.xml から非ルート要素をコピーします。

<xsl:template match="state">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()" />
     <xsl:copy-of
      select="document('file2.xml')
            /config/state[@version = current()/@version]/*[not(self::root)]" />
  </xsl:copy>
</xsl:template>

ここに完全な XSLT があります

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

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

   <xsl:template match="state">
      <xsl:copy>
         <xsl:apply-templates select="@* | node()"/>
         <xsl:copy-of select="document('file2.xml')
              /config/state[@version = current()/@version]
                     /*[not(self::root)]"/>
      </xsl:copy>
   </xsl:template>

   <xsl:template match="root">
      <xsl:copy>
         <xsl:apply-templates select="@* | node()"/>
         <xsl:copy-of select="document('file2.xml')
              /config/state[@version = current()/../@version]
                     /root[@value = current()/@value and
                           @group = current()/@group]/*"/>
      </xsl:copy>
   </xsl:template>
</xsl:stylesheet>

2 つの XML ファイルに適用すると、次のように出力されます。

<config>
   <state version="10">
      <root value="100" group="5">
         <leaf number="2"/>
         <leaf number="6"/>
      </root>
      <action value="2" step="4">
         <get score="5"/>
      </action>
      <parent>
         <child node="yes"/>
      </parent>
   </state>
</config>
于 2013-02-05T13:15:32.730 に答える