Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate though each child node in an XML file?

Tags:

c#

xml

I have an XML File and i would like to iterate though each child node gathering information.

Here is my C# code it only picks up one node, the FieldData i would like to use a foreach on its child nodes.

public void LoadXML() {
    if (File.Exists("Data.xml")) {
        //Reading XML
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("Data.xml");

        //Think something needs to reference Child nodes, so i may Foreach though them

        XmlNodeList dataNodes = xmlDoc.SelectNodes("//FieldData"); 
        TagContents[] ArrayNode;

        foreach(XmlNode node in dataNodes) {
            int Count = 0;
            //int Max = node.ChildNodes.Count;
            ArrayNode = new TagContents[Max];

            ArrayNode[Count].TagName = node.Name;
            ArrayNode[Count].TagValue = node.SelectSingleNode(ArrayNode[Count].TagName).InnerText;
            Count = Count + 1;        
        }
    } else {
        MessageBox.Show("Could not find file Data.xml");
    }
}

My XML Looks Something like:

<?xml version="1.0"?>
<FieldData>
  <property_details_branch IncludeInPDFExport="Yes" Mod="20010101010101"/>
  <property_details_inspection_date IncludeInPDFExport="Yes" Mod="20120726200230">20120727220230+0200</property_details_inspection_date>
  <property_details_type_of_ownership IncludeInPDFExport="Yes" Mod="20120726134107">Freehold</property_details_type_of_ownership>
</FieldData>
like image 914
Pomster Avatar asked Aug 01 '12 12:08

Pomster


3 Answers

You're iterating the FieldData nodes and you have only one. To iterate its child nodes write:

foreach (XmlNode node in dataNodes)
{
     foreach (XmlNode childNode in node.ChildNodes)
     {
like image 136
Amiram Korach Avatar answered Oct 07 '22 02:10

Amiram Korach


I generally prefer Linq-To-Xml for this kind of thing:

  var doc = XDocument.Load("XMLFile1.xml");
  foreach (var child in doc.Element("FieldData").Elements())
  {
    Console.WriteLine(child.Name);
  }
like image 36
lesscode Avatar answered Oct 07 '22 03:10

lesscode


Or you use recursion:

    public void findAllNodes(XmlNode node)
    {
        Console.WriteLine(node.Name);
        foreach (XmlNode n in node.ChildNodes)
            findAllNodes(n);
    }

Where do you place the payload depends on what kind of search you want to use (e.g. breadth-first search, depth-first search, etc; see http://en.wikipedia.org/wiki/Euler_tour_technique)

like image 5
Jan Avatar answered Oct 07 '22 04:10

Jan