PDA

View Full Version : code for merging one XML into another



Mike
26-05-2014, 06:42 PM
I may need to go to an XML or programming forum of some sort, but I'll try here first :)

I have an XML file I receive from a third party, and an application that needs to import the XML, but needs extra XML entries and some reordered etc. for it to work. I've figured out where most of it needs to go but am wondering if there's a way to script the process as this isn't a one-off and will be needed often. The XML in the first won't always contain the same keys and same data (but close to it) so I can't just map the same parts from one to the other.

Is there a way using .Net or Python or *something* to read each key and subkey etc. from one XML and write each one into the correct location in the second XML?



<key1 value="Key 1">
<subkey1>Hello</subkey1>
<subkey2>World</subkey2>
</key1>
<key2 value="Key 2">
<subkey1>Goodbye</subkey1>
<subkey2>Goodnight</subkey2>
</key2>




<newkey1>
<key1 value="Key 1">
<subkey1>Hello</subkey1>
</key1>
<key2 value="Key 2">
<subkey1>Goodbye</subkey1>
</key2>
</newkey1>
<newkey2>
<key1 value="Key 1">
<subkey2>World</subkey2>
</key1>
<key2 value="Key 2">
<subkey2>Goodnight</subkey2>
</key2>
</newkey2>


OK so it's a pretty bad example, but it's the basic idea. Some of the parts of XML 1 have been moved slightly but mostly they fit into the same keys, some are repeated. I don't see this as being too difficult to step through, I'm just not sure quite how to get it started.

Any suggestions?

Thanks,
Mike.

Ofthesea
26-05-2014, 11:45 PM
Sounds like an XSLT situation, insert newkey1, search on key 1 etc

kingdragonfly
27-05-2014, 01:33 PM
A Dotnet program will definitely handle this. However it has a very steep learning curve.

You'll be heavily using this library. In C#, it looks like this.
using System.Xml;

You may also need the very-hard-to-use "XPath"

This may get you started:

http://csharp.net-tutorials.com/xml/writing-xml-with-the-xmldocument-class/

Mike
28-05-2014, 12:27 PM
I was overthinking it :D I got Python to read the input XML one line at a time and copy to the right location in the Output XML line-by-line. I've probably written it fairly inefficiently but it runs so fast I'd never notice. Can do 27 XML files of about 800 lines each in under a second.

Cheers,
Mike.

kingdragonfly
28-05-2014, 01:02 PM
Reading the XML as a text file definitely uses less resources, as there's little or no validation.

However, speed always come with a price.

Note that these two XML documents are equivalent:


<results><Reference>{REFERENCE-HERE}</Reference></results>

<results>

<Reference>{REFERENCE-HERE}</Reference>
</results>