views:

36

answers:

2

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>
            <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>
A: 

Install Java and use XmlMerge.

You may also find XML Merger useful.

taspeotis
A: 

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"&gt;
  <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
Jukka Matilainen