Breaking News

Wednesday, September 29, 2010

How to: Merge Multiple Xmls?

Easiest, simplest, fastest way? ...could be, well, if you don't want any checks to be performed(duplicates, zombies, etc), and are using .NET 3.5 or above:

var ResultXml = XDocument.Load("file1.xml");
ResultXml.Root.Add(XDocument.Load("file2.xml").Root.Elements());

Cool, right? (0:
Or if you are "still" a fan of pre-date'rs, use XmlDocument:

static void AppendChildren(XmlWriter xmlWriter, string strFilePath)
{
    using (XmlReader xmlReader = XmlReader.Create(strFilePath))
    {
        xmlReader.MoveToContent();
        int nDepth = xmlReader.Depth + 1;
        if (xmlReader.Read())
        {
            while (xmlReader.Depth == nDepth)
            {
                xmlWriter.WriteNode(xmlReader, true);
            }
        }
    }
}

Or better, if you want, would be to make it an extention method:

static void AppendChildren(this XmlWriter xmlWriter, string strFilePath)

All you have to do is to call .ToAppendChildren() method.

Happy programming! (0:

No comments:

Post a Comment

Designed By Published.. Blogger Templates