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
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 lstChildElements = new List();
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(XMLFileLocation);
{
List
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);
}
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);
}
}