开发者

Is there any way to get the combine two xml into one xml in Linux

XML one is something like that:

<dict>
    <key>2</key>
    <array>
        <string>A</string>
        <string>B</string>
    </array>
    <key>3</key>
    <array>
        <string>C</string>
        <string>D</string>
        <string>E</string>
    </array>
</dict>      

XML Two is something like that:

<dict>
    <key>A</key>
    <array>
        <string>A1</string>
        <false/>
        <false/>
        <array>
            <string>Apple</string>
            <string>This is an apple</string>
        </array>
        <array>
            <string>Apple Pie</string>
            <string>I love Apple Pie.</string>
        </array>
    </array>
    <key>B</key>
    <array>
        <string>B7</string>
        <false/>
        <false/>
        <array>
开发者_如何学Python            <string>Boy</string>
            <string>I am a boy.</string>
        </array>
    </array>
</dict>

I want to convert to this:

<dict>
    <key>2</key>
    <array>
        <string>A, Apple, Apple Pie</string>
        <string>B, Boy</string>
    </array>
    ...
</dict>


You could do it using XSLT by applying the following stylesheet on the first XML file, assuming the second XML file is named two.xml:

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
  <xsl:key name="string-by-key"
           match="/dict/array/array/string[1]"
           use="preceding::key[1]"/>
  <xsl:template match="dict">
    <dict>
      <xsl:apply-templates select="key"/>
    </dict>
  </xsl:template>
  <xsl:template match="key">
    <key>
      <xsl:value-of select="."/>
    </key>
    <array>
      <xsl:apply-templates select="following-sibling::array[1]/string"/>
    </array>
  </xsl:template>
  <xsl:template match="string">
    <string>
      <xsl:variable name="key" select="."/>
      <xsl:value-of select="$key"/>
      <xsl:for-each select="document('two.xml')">
        <xsl:for-each select="key('string-by-key', $key)">
          <xsl:text>, </xsl:text>
          <xsl:value-of select="."/>
        </xsl:for-each>
      </xsl:for-each>
    </string>
  </xsl:template>
</xsl:stylesheet>

The key tricks here (no pun intended) are

  1. the use of xsl:key to index the strings by their key to allow easy and quick lookup, and
  2. changing the context node to the second XML file using xsl:for-each before calling the key function.

Edit. Since you asked specifically about Linux, you can use the xsltproc program to apply the XSLT stylesheet to your input file like this:

xsltproc stylesheet.xsl one.xml


Install Java and use XmlMerge.

You may also find XML Merger useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜