如何迭代XML文件中的每个子节点?

我有一个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看起来像:

    20120727220230+0200 Freehold  

您正在迭代FieldData节点,而您只有一个。 要迭代其子节点,请执行以下操作:

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

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

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

或者你使用递归:

  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 )

你可以这样做:

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

刚刚接触@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 } 
  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 } 

要遍历每个子节点,子子节点等,我们必须使用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; }