Monday, 22 April 2013

How to get child nodes of an element in an XML in a WPF application?

How to get child nodes of an element in an XML in a WPF application? 
 
While parsing an XML in a WPF application, I fell in a need to fetch the child nodes of an element. I put the question on stackoverflow and got many responses but at last I was able to answer that question myself.
 
Lets consider the problem:
 
Suppose I have following XML
 
<Loop Name="MasterData">
  <Loop Name="SlaveData">
    <Segment Name="AAA">
      <Node1>hello</Node1>
      <Node2>john</Node2>
      <Node3>hi</Node3>
      <Node4>marry</Node4>
    </Segment>
    <Segment Name="BBB">
      <Node1>00</Node1>
      <Node2> </Node2>
      <Node3>00</Node3>
      <Node4> </Node4>
    </Segment>
   </Loop>
</Loop>  
 
Now I have to get the values of Node1, Node2, Node3, Node4 ie, hello, john, hi, marry in a list whose parent element is Segment with Name as "AAA". So first of all I will try to reach at segment with name attribute as "AAA" and then I will check whether that elements has child nodes or not. If that segment element contains child nodes, then I will fetch the innertext of all the child nodes.
 
Below is the C# code for fetching the child nodes of an element
 
public static void GetChildElements()
{
    List<string> lstChildElements = new List<string>();
   XmlDocument xmlDocument = new XmlDocument();
   xmlDocument.Load(XMLFileLocation);

   XmlNodeList xnList = xmlDocument.SelectNodes("/Loop/Loop/Segment[@Name='AAA']");
   foreach (XmlNode xn in xnList)
   {
     if (xn.HasChildNodes)
     {
       foreach (XmlNode childNode in xn.ChildNodes)
       {
          lstISAElements.Add(childNode.InnerText.ToString());
       }
     }
   }
   foreach (string childElement in lstChildElements)
   {
     Console.WriteLine(childElement);
   }
     
}

No comments:

Post a Comment