简体   繁体   中英

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

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>

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)
     {

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);
  }

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 (eg breadth-first search, depth-first search, etc; see http://en.wikipedia.org/wiki/Euler_tour_technique )

You can do it like this:

    XDocument doc = XDocument.Load(@"Data.xml");
    TagContents[] ArrayNode = doc.Root
                                .Elements()
                                .Select(el =>
                                    new TagContents()
                                    {
                                        TagName = el.Name.ToString(),
                                        TagValue = el.Value
                                    })
                                .ToArray();

Just touching on @Waynes answer, which worked well. I used the below code to push further into the child nodes in my xml

foreach (var child in doc.Element("rootnodename").Element("nextchildnode").Elements()) 

{

 //do work here, probs async download xml content to file on local disc

} 
    public void ValidateXml(string[] Arrays)
    {                                         
        foreach (var item in Arrays)
        {
            Xdoc.Load(item);                              
            XmlNodeList xnList = Xdoc.SelectNodes("FirstParentNode");
            if (xnList.Count > 0)
            {
                foreach (XmlNode xn in xnList)
                {
                    XmlNodeList anode = xn.SelectNodes("SecondParentNode");
                    if (anode.Count > 0)
                    {
                        foreach (XmlNode bnode in anode)
                        {                               
                            string InnerNodeOne = bnode["InnerNode1"].InnerText;
                            string InnerNodeTwo = bnode["InnerNode1"].InnerText;

                        }                           
                    }
                    else
                    {
                        ErrorLog("Parent Node DoesNot Exists");                                                 
                    }
                }                  
            }
            else
            {
                ErrorLog("Parent Node DoesNot Exists");
            }

        }
       //then insert or update these values in database here
    }

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM