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

Viewed 96702

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>
7 Answers

To iterate through each and every child node, sub-child node and so on, We have to use Recursion. In case someone have the same requirement as I had, I achieved this something like below -

public string ReadAllNodes(XmlNode node)
{
    if (node.ChildNodes.Count > 0)
    {
        foreach (XmlNode subNode in node)
        {
            //Recursion
            ReadAllNodes(subNode);
        }
    }
    else //Get the node value.
    {
        finalText = finalText + node.InnerText + System.Environment.NewLine;
    }
    return finalText;
}
Related