If I have two string of xml1 and xml2 which both represent xml in the same format. What is the fastest way to combine these together? The format is not important, but I just want to know how can I get rid off or ?
xml1 :
<?xml version="1.0" encoding="utf-8"?>
<AllNodes>
<NodeA>
<NodeB>test1</NodeB>
<NodeB>test2</NodeB>
</NodeA>
</AllNodes>
xm2 :
<?xml version="1.0" encoding="utf-8"?>
<AllNodes>
<NodeA>
<NodeB>test6</NodeB>
<NodeB>test7</NodeB>
</NodeA>
<NodeA>
<NodeB>test99</NodeB>
<NodeB>test23</NodeB>
</NodeA>
</AllNodes>
and have something like this :
<?xml version="1.0" encoding="utf-8"?>
<AllNodes>
<NodeA>
<NodeB>test1</NodeB>
<NodeB>test2</NodeB>
</NodeA>
<NodeA>
<NodeB>test6</NodeB>
<NodeB>test7</NodeB>
</NodeA>
<NodeA>
<NodeB>test99</NodeB>
<NodeB>test23</NodeB>
</NodeA>
</AllNodes>
The easiest way to do this is using LINQ to XML. You can use either Union or Concat depending on your needs.
Since you asked for the fastest:
If (and only if) the xml structure is always consistent: (this is pseudo code)
It's a giant hack but it's fast. Expect to see it on TheDailyWTF when your colleagues find it.
In my case the main solution did not work well, the difference was that I had a List for a thousands of files when I take one element and try to merge with the first element I get OutOfMemory exception, I added an empty template with and empty row (NodeA in this case) to solve the weird problem of the memory and run smoothly.
I save the document in other process
This is the fastest and cleanest way to merge xml files.
You have two basic options:
Parse the xml, combine the data structures, serialize back to xml.
If you know the structure, use some basic string manipulation to hack it. For example, in the example above you could take the inside of allnodes in the two xml blocks and put them in a single allnodes block and be done.
If you want to use the XmlDocument, try this