9

XSLT を使用して 1 つにマージする必要がある 2 つの xml ファイルがあります。

最初の XML は (元のもの):

<feed>
  <author> 
    <firstName>f</firstName>
    <lastName>l</lastName>
  </author>
  <date>2011-01-02 </date>
  <entry>
    <id>1</id>
    <Name>aaa</Name>
    <Content>XXX</Content>     
  </entry>
  <entry>
    <id>2</id>
    <Name>bbb</Name>
    <Content>YYY</Content>   
  </entry>
</feed>

2 番目の XML (更新されたデータ) は次のようになります。

   <feed>
      <author> 
       <firstName>f</firstName>
       <lastName>l</lastName>
      </author>
      <date>2012-05-02 </date>
      <entry>
        <id>2</id>
        <Name>newName</Name>
        <Content>newContent</Content>     
      </entry>
      <entry>
        <id>3</id>
        <Name>ccc</Name>
        <Content>ZZZ</Content>   
      </entry>
  </feed>

目的のマージ結果 - 2 番目の XML を使用して最初の XML を更新します。

 <feed>
      <author> 
       <firstName>f</firstName>
       <lastName>l</lastName>
      </author>
      <date>2012-05-02 </date>
      <entry>
        <id>1</id>
        <Name>aaa</Name>
        <Content>XXX</Content>     
      </entry>     
      <entry>
        <id>2</id>
        <Name>newName</Name>
        <Content>newContent</Content>     
      </entry>
      <entry>
        <id>3</id>
        <Name>ccc</Name>
        <Content>ZZZ</Content>   
      </entry>
   </feed>

stackoverflow を検索しましたが、まだ答えが見つかりませんでした。手伝ってくれてありがとう。

4

1 に答える 1

16

前回の質問に回答したのとほぼ同じ回答を、新しい XML 形式に合わせて修正しました。

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
  <xsl:param name="fileName" select="'updates.xml'" />
  <xsl:param name="updates" select="document($fileName)" />

  <xsl:variable name="updateItems" select="$updates/feed/entry" />

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

  <xsl:template match="feed">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()[not(self::entry)] | 
                                   entry[not(id = $updateItems/id)]" />
      <xsl:apply-templates select="$updateItems" />
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

最初のサンプル XML で実行し、2 番目のサンプル XML を「updates.xml」として保存すると、次のようになります。

<feed>
  <author>
    <firstName>f</firstName>
    <lastName>l</lastName>
  </author>
  <date>2011-01-02 </date>
  <entry>
    <id>1</id>
    <Name>aaa</Name>
    <Content>XXX</Content>
  </entry>
  <entry>
    <id>2</id>
    <Name>newName</Name>
    <Content>newContent</Content>
  </entry>
  <entry>
    <id>3</id>
    <Name>ccc</Name>
    <Content>ZZZ</Content>
  </entry>
</feed>
于 2013-03-04T07:20:33.177 に答える