Quantcast
Viewing all articles
Browse latest Browse all 8

Answer by Rachel for How can I merge XML files?

I ended up using C# and created myself a script. I knew I could do it when I asked the question, but I wanted to know if there was a faster way to do this since I've never really worked with XML.

The script went along the lines of this:

var a = new XmlDocument();a.Load(PathToFile1);var b = new XmlDocument();b.Load(PathToFile2);MergeNodes(    a.SelectSingleNode(nodePath),    b.SelectSingleNode(nodePath).ChildNodes,    a);a.Save(PathToFile1);

And MergeNodes() looked something like this:

private void MergeNodes(XmlNode parentNodeA, XmlNodeList childNodesB, XmlDocument parentA){    foreach (XmlNode oNode in childNodesB)    {        // Exclude container node        if (oNode.Name == "#comment") continue;        bool isFound = false;        string name = oNode.Attributes["Name"].Value;        foreach (XmlNode child in parentNodeA.ChildNodes)        {            if (child.Name == "#comment") continue;            // If node already exists and is unchanged, exit loop            if (child.OuterXml== oNode.OuterXml&& child.InnerXml == oNode.InnerXml)            {                isFound = true;                Console.WriteLine("Found::NoChanges::"+ oNode.Name +"::"+ name);                break;            }            // If node already exists but has been changed, replace it            if (child.Attributes["Name"].Value == name)            {                isFound = true;                Console.WriteLine("Found::Replaced::"+ oNode.Name +"::"+ name);                parentNodeA.ReplaceChild(parentA.ImportNode(oNode, true), child);            }        }        // If node does not exist, add it        if (!isFound)        {            Console.WriteLine("NotFound::Adding::"+ oNode.Name +"::"+ name);            parentNodeA.AppendChild(parentA.ImportNode(oNode, true));        }    }}

Its not perfect - I have to manually specify the nodes I want merged, but it was quick and easy for me to put together and since I have almost no knowledge of XML, I'm happy :)

It actually works out better that it only merges the specified nodes since I'm using it to merge Entity Framework's edmx files, and I only really want to merge the SSDL, CDSL, and MSL nodes.


Viewing all articles
Browse latest Browse all 8

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>