How to check if an XML node exists in the children of another node?

3.5k views Asked by At

I want to add an XmlNode to another XmlNode if it doesn't contain this node (the comparison should be based on the node name and its contents)

System.Xml.XmlDocument doc;
...
XmlNode newNode = doc.CreateElement(name);
newNode.InnerXml = something
XmlNode parentNode = doc.GetElementsByTagName(parentName);
if (parentNode.???? (newNode))
{
    parentNode.AppendChild(newNode);
}

How can I check this existence? parentNode.ChildNodes doesn't have a Contain method.

2

There are 2 answers

0
DPH On

I think this will do the trick:

    private void doSomething() 
    {
        XmlDocument doc = new XmlDocument();
        XmlNode newNode = doc.CreateElement("name");
        newNode.InnerXml = "something";
        XmlNode parentNode = doc.GetElementsByTagName("parentName")[0]; 
            // I just stuck an index on end of above line... 
            // Note that GetElementsByTagName returns an XmlNodeList

        int huh = 0;
        foreach (XmlNode n in parentNode.ChildNodes)
        {
            // If I understood you correctly, you want these checks?
            if (n.InnerXml == newNode.InnerXml && n.Name == newNode.Name) huh++;
        }

        if (huh == 0) parentNode.AppendChild(newNode);
    }
0
Charles Mager On

You could do this using LINQ to XML making use of the XNode.DeepEquals method to compare your child nodes for equality. An example might look like this - the duplicateChild will not be added but newChild will be:

var doc = new XDocument(
    new XElement("parent",
        new XElement("child", 1)));

var parent = doc.Descendants("parent").Single();

var duplicateChild = new XElement("child", 1);
var newChild = new XElement("child", 2);

if (!parent.Elements().Any(e => XNode.DeepEquals(e, duplicateChild)))
{
    parent.Add(duplicateChild);
}

if (!parent.Elements().Any(e => XNode.DeepEquals(e, newChild)))
{
    parent.Add(newChild);
}

A demo here: https://dotnetfiddle.net/1t4Q1b