I am trying to merge several XML files in a single XDocument object.
Merge does not exist in XDocument object. I miss this.
Has anyone already implemented a Merge extension method for XDocument, or something similar ?
To use this, create a new XSLT file (File > New > XSLT Stylesheet and place in it the stylesheet above. Save the file as "merge. xsl". You should also add the files (or folder) to an Oxygen project (Project view) and create a scenario of the "XML transformation with XSLT" type for one XML file.
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);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With