C# 如何遍历 XML 文件中的每个子节点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11759426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:07:52  来源:igfitidea点击:

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

c#xml

提问by Pomster

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

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

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

这是我的 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");
    }
}


My XML Looks Something like:

我的 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>

采纳答案by Amiram Korach

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

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

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

回答by lesscode

I generally prefer Linq-To-Xmlfor this kind of thing:

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

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

回答by Ivan G

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

回答by Jan

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)

您将有效负载放在哪里取决于您要使用的搜索类型(例如广度优先搜索、深度优先搜索等;请参阅http://en.wikipedia.org/wiki/Euler_tour_technique

回答by BENN1TH

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

只是触及@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

} 

回答by Gaurav Dubey

    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
    }

回答by Arpit Gupta

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 -

要遍历每个子节点、子子节点等,我们必须使用Recursion. 如果有人和我有相同的要求,我实现了如下所示 -

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