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 ju
Best solution to me, based on Jose Basilio answer, slightly modified,
var combinedUnique = xml1.Descendants()
.Union(xml2.Descendants());
combinedUnique.First().Save(#fullName)
Since you asked for the fastest:
If (and only if) the xml structure is always consistent: (this is pseudo code)
string xml1 = //get xml1 somehow
string xml2 = //get xml2 somehow
xml1 = replace(xml1, "<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
xml1 = replace(xml1, "<allnodes>", "");
xml1 = replace(xml1, "</allnodes>", "");
xml2 = replace(xml2, "<allnodes>", "<allnodes>\n" + xml1);
It's a giant hack but it's fast. Expect to see it on TheDailyWTF when your colleagues find it.
The easiest way to do this is using LINQ to XML. You can use either Union or Concat depending on your needs.
var xml1 = XDocument.Load("file1.xml");
var xml2 = XDocument.Load("file2.xml");
//Combine and remove duplicates
var combinedUnique = xml1.Descendants("AllNodes")
.Union(xml2.Descendants("AllNodes"));
//Combine and keep duplicates
var combinedWithDups = xml1.Descendants("AllNodes")
.Concat(xml2.Descendants("AllNodes"));
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 can guarantee this format you can combine them by doing string manipulation:
This should be the fastest way since no parsing is needed.
const string RelevantTag = "AllNodes";
string xml1 = File.ReadAllText(xmlFile1);
xml1 = xml1.Substring(0, xml.LastIndexOf("</" + RelevantTag + ">"));
string xml2 = File.ReadAllText(xmlFile2);
xml2 = xml2.Substring(xml.IndexOf("<" + RelevantTag + ">") + "<" + RelevantTag + ">".Length, xml1.Length);
File.WriteAllText(xmlFileCombined, xm1 + xml2);
That said I would always prefer the safe way to the fast way.