Pages

Tuesday 23 April 2013

How to show value of attributes of child nodes of an element in C#?

How to show value of attributes of child nodes of an element in C#?
 
Lets say you have following XML and you have to fetch IDs of Element tags which are under Segments/Segment/Elements. In this case you have to use SelectNodes method to reach upto desired nodes and then take it to the XMLNodeList. Iterate the list check its child nodes and get the attributes of child nodes. I think below code can clear what I am trying to say.
 
My XML File
 
<?xml version="1.0" encoding="utf-8"?>
    <Segments>
        <Segment ID="AAA">
            <Elements>
                <Element ID ="11" />
                <Element ID ="22" El/>
                <Element ID ="33" />
            </Elements>
         </Segment>
    </Segments> 
  
My C# code
 
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(MyXMLFileLocation);
XmlNodeList xnList = xmlDocument.SelectNodes(/Segments/Segment[@ID='AAA']/Elements);
foreach (XmlNode xn in xnList)
{
    if (xn.HasChildNodes)
    {
        foreach (XmlNode childNode in xn.ChildNodes)
        {
            Console.Writeline(childNode.Attributes["ID"].Value);
         }
    } 
}

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.