Search code examples
c#.netxmltraversal

In XML, check if child nodes contain specific values with C#


I'm getting back some XML and this is a section of it:

<pair name="cf_item7" type="pair">
    <pair name="cf_id" type="integer">34</pair>
    <pair name="value" type="string">0</pair>
</pair>

Within the XML are a number of pairs. The section I need to check with always have a name beginning with cf_item* but this could be cf_item7, cf_item6, or any other number.

I need to check within one of these cf_item* sections, and whether or not it has a cf_id, with the content equalling 34 (it will always be 34).

If 34 exists, I need to check the next node (value), and check if it is equal to 0 or 1.

If it equals 0, I need to output a message to the screen (web page).

I've inherited the original code, which is written in C# .net - Can anyone help as it's not a language I'm familiar with?

I started with this, based on some of the other code, but I'm unsure where to go next.

if (eleName.Contains("cf_item")) {
     XmlNode nodes = eleList[i].ChildNodes;
}

Solution

  • First, get the first element with pair name then check if the name attribute contains cf_item. If yes, get all elements with pair name from that first element.

    The result will be in an IEnumerable<XElement> then you can check the first element if it contains 34 and if the second element contains 0 or not.

    The code will be something like this:

    XDocument xmldata = XDocument.Load(xmlFile);
    XElement node = xmldata.Element("pair");
    if (node.Attribute("name").Value.Contains("cf_item"))
    {
           IEnumerable<XElement> nextElmts = node.Elements("pair");
           if (nextElmts.ElementAt(0).Attribute("name").Value.Contains("cf_id"))
           {
               if ((Convert.ToInt32(nextElmts.ElementAt(0).Value) == 34))
               {
                    if (Convert.ToInt32(nextElmts.ElementAt(1).Value) == 0)
                    {
                         //do what you want here
                         Console.WriteLine("it's 0");
                    }
               }
           }
    }
    

    Note: this is only for one cf_item. You need to modified it if cf_item is more than one.