如何在XML文件中迭代遍历每个子节点?

20

我有一个XML文件,想要迭代遍历每个子节点并收集信息。

这是我的C#代码,它只获取了一个节点,即FieldData,我想在其子节点上使用foreach。

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");
    }
}
我的XML长这样:
<?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>

我只想指出,在你的foreach循环中,你将Count设置为零,然后执行一些操作,递增它,最后又将其设置回零。 - user4734394
7个回答

27

您正在迭代FieldData节点,而且只有一个。要迭代它的子节点,请编写:

foreach (XmlNode node in dataNodes)
{
     foreach (XmlNode childNode in node.ChildNodes)
     {

1
应该不是foreach (XmlNode childNode in node.ChildNodes)吗? - Rox
1
我建议您查看关于XDocument的其他答案。您应该使用它而不是XmlDocument。 - Amiram Korach
1
请注意,如果有人决定在<FieldData>下添加注释或文本节点,您的循环也会将它们捕获。 - lesscode
我认为这段代码只会迭代到第二级,如果在第二级有子节点,它将不会返回其值。 - Arpit Gupta

8

对于这种情况,我通常更喜欢使用Linq-To-Xml

  var doc = XDocument.Load("XMLFile1.xml");
  foreach (var child in doc.Element("FieldData").Elements())
  {
    Console.WriteLine(child.Name);
  }

5

或者您可以使用递归:

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

你需要根据你想使用的搜索方法(如广度优先搜索,深度优先搜索等)来确定负载的放置位置;详见http://en.wikipedia.org/wiki/Euler_tour_technique


2
你可以这样做:
    XDocument doc = XDocument.Load(@"Data.xml");
    TagContents[] ArrayNode = doc.Root
                                .Elements()
                                .Select(el =>
                                    new TagContents()
                                    {
                                        TagName = el.Name.ToString(),
                                        TagValue = el.Value
                                    })
                                .ToArray();

0

仅涉及@Waynes的答案,它很有效。我使用以下代码进一步推入我的xml中的子节点

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

{

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

} 

0
要遍历每个子节点、子子节点等等,我们必须使用“递归”。如果有人有和我一样的需求,可以像下面这样实现:
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;
}

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

如果有更多级别的父节点呢?我认为你的代码在那时会出错。 - Arpit Gupta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接