user1730861
user1730861

Reputation: 21

How to find child dynamically inside XML

how to check whether child node is there for the product node in the following xml:

   <product>
        <SysSectionName>Processors</SysSectionName>
        <section>
          <subsection>
            <SysSectionName>CPU#1</SysSectionName>
          </subsection>
       </section>
  </product>

I have tried this:

foreach (XmlNode xn1 in sectionNode)
{
  XmlNode node = xn1.FirstChild; 
  if (xn1.HasChildNodes)
  {
     //do something..
  }     
}

Upvotes: 1

Views: 376

Answers (4)

Ashwini Verma
Ashwini Verma

Reputation: 7525

XmlNodeList snode = xmldoc.SelectNodes("/product/section/subsection");
foreach (XmlNode xn2 in snode)
{
    //it comes inside if there will be a child node.
}

Upvotes: 1

Artak
Artak

Reputation: 2887

I think XLinq (Linq for Xml) is what you're looking for. Then you should load the Xml using XDocument, and for any XElement you have the "Descendants()" method, which returns list of child XElements. If there are no child elements, the list will have no elements as well.

Upvotes: 0

Milind Thakkar
Milind Thakkar

Reputation: 980

You mean you want to find whether product node has any child node? If yes,

XmlNodeList productNodes = xmlDoc.SelectNodes("Product");
foreach(XmlNode pNode in productNodes)
{
  if(pNode.ChildNodes.count >0)
  {
  }
}

Upvotes: 0

Furqan Safdar
Furqan Safdar

Reputation: 16718

Try to use this piece of code to get the product nodes from XML:

XDocument doc = XDocument.Parse("Your Xml String");

var products = doc.Descendants("product");

foreach (var product in products)
{
    //... do something ...
}

Upvotes: 1

Related Questions