views:

1143

answers:

3

Hello,

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 ?

A: 

As a workaround, you could use a XSL file to merge the XML files and then transform it to a XDocument object.

schnaader
Thank you. I'm sorry, I hate XSL. I would definitely prefer a c# code based solution.
controlbreak
No problem, I understand XSL avoidance as it can be very confusing sometimes.
schnaader
+3  A: 

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);
                }                
            }
        }
    }
Marc Gravell
Thanks a lot :) I think I have found something that works with less code.
controlbreak
+6  A: 

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

controlbreak