Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge XML files in a XDocument

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 ?

like image 574
Larry Avatar asked Nov 11 '08 08:11

Larry


People also ask

Can we merge two XML files?

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.


2 Answers

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 :-)

like image 90
Larry Avatar answered Sep 19 '22 15:09

Larry


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);
                }                
            }
        }
    }
like image 31
Marc Gravell Avatar answered Sep 21 '22 15:09

Marc Gravell