Merge XML files in a XDocument
I tried a bit myself :
var MyDoc = XDocument.Load("File1.xml");MyDoc.Root.Add(XDocument.Load("File2.xml").Root.Elements());
I dont know whether it is good or bad, but it works fine to me :-)
Being pragmatic, XDocument
vs XmLDocument
isn't all-or-nothing (unless you are on Silverlight) - so if XmlDoucument
does something you need, and XDocument
doesn't, then perhaps use XmlDocument
(with ImportNode
etc).
That said, even with XDocument
, you could presumably use XNode.ReadFrom
to import each, then simply .Add
it to the main collection.
Of course, if the files are big, XmlReader/XmlWriter
might be more efficient... but more complex. Fortunately, XmlWriter
has a WriteNode
method that accepts an XmlReader
, so you can navigate to the first child in the XmlReader
and then just blitz it to the output file. Something like:
static void AppendChildren(this XmlWriter writer, string path) { using (XmlReader reader = XmlReader.Create(path)) { reader.MoveToContent(); int targetDepth = reader.Depth + 1; if(reader.Read()) { while (reader.Depth == targetDepth) { writer.WriteNode(reader, true); } } } }
Merge all xml files from dir to one XDocument
public static XDocument MergeDir(string xmlDir){ XDocument xdoc = XDocument.Parse("<root></root>"); System.IO.DirectoryInfo directory = new DirectoryInfo(xmlDir); if (directory.Exists) { foreach (System.IO.FileInfo file in directory.GetFiles()) { if (file.Extension == ".xml") { xdoc.Root.Add(XDocument.Load(file.FullName).Root.Elements()); } } } return xdoc;}