tags:

views:

170

answers:

2

Hi, Occasionally, one or more XML Elements are missing from XML File. Right now, one work around i am thinking is to compare XML file with a master XML File (having all the elements) and if any element is missing then add that element in XML File from master file.

How i gonna achieve this or any other better idea?

A: 

From link text

using System.Xml;

public class Form1
{

XmlDocument Doc1;
XmlDocument Doc2;

string Doc1Path = "C:\\XmlDoc1.xml";

private void Form1_Load(object sender, System.EventArgs e)
{

    Doc1 = new XmlDocument();
    Doc2 = new XmlDocument();

    Doc1.Load(Doc1Path);
    Doc2.Load("C:\\XmlDoc2.xml");

    Compare();

    Doc1.Save(Doc1Path);

}

public void Compare()
{

    foreach (XmlNode ChNode in Doc2.ChildNodes) {
        CompareLower(ChNode);
    }

}

public void CompareLower(XmlNode NodeName)
{

    foreach (XmlNode ChlNode in NodeName.ChildNodes) {

        if (ChlNode.Name == "#text") {
            continue;
        }

        string Path = CreatePath(ChlNode);

        if (Doc1.SelectNodes(Path).Count == 0) {
            XmlNode TempNode = Doc1.ImportNode(ChlNode, true);
            Doc1.SelectSingleNode(Path.Substring(0, Path.LastIndexOf("/"))).AppendChild(TempNode);
            Doc1.Save(Doc1Path);
        }
        else {
            CompareLower(ChlNode);
            Doc1.Save(Doc1Path);
        }

    }

}

public string CreatePath(XmlNode Node)
{

    string Path = "/" + Node.Name;

    while (!(Node.ParentNode.Name == "#document")) {
        Path = "/" + Node.ParentNode.Name + Path;
        Node = Node.ParentNode;
    }
    Path = "/" + Path;
    return Path;

}

}

John M
The only problem with this is it's an exponential time algorithm. You need something that does look at each element in doc1 for each element in doc2.
highphilosopher
+1  A: 

One of the coolest libraries I've found while just looking around the Microsoft site is the XmlDiffPatch library. You can find more information at http://msdn.microsoft.com/en-us/library/aa302294.aspx but it essentially allows you to compare two documents, find all the differences and then apply those differences. Very useful for compressing xml files to send across a network

LorenVS
Ya. its a cool stuff...but not gonna help in my case. I need to compare only elements (ignore Inner Text value), and if element is missing add a blank element.
Novice
Aaah... Sorry, I didn't catch that from your question... Well, more people should know about the DiffPatch library regardless...
LorenVS
Actually this solves your problem perfectly - just make sure the master XML contains blank elements.
orip
Good point, I suppose it would work with a little bit of xml manipulation
LorenVS