当前位置: 首页 > 编程语言 > C#

如何遍历XML文件中的每个子节点?分享

时间:2023-04-10 23:38:52 C#

如何遍历XML文件中的每个子节点?我有一个XML文件,我想遍历每个子节点来收集信息。这是我的C#代码,它只获取一个节点FieldData我想在其子节点上使用foreach。publicvoidLoadXML(){if(File.Exists("Data.xml")){//读取XMLXmlDocumentxmlDoc=newXmlDocument();xmlDoc.Load("Data.xml");//认为有些东西需要引用子节点,所以我可以通过它们ForeachXmlNodeListdataNodes=xmlDoc.SelectNodes("//FieldData");TagContents[]ArrayNode;foreach(数据节点中的XmlNode节点){intCount=0;//intMax=node.ChildNodes.数数;ArrayNode=newTagContents[Max];ArrayNode[Count].TagName=node.Name;ArrayNode[Count].TagValue=node.SelectSingleNode(ArrayNode[Count].TagName).InnerText;计数=计数+1;}}else{MessageBox.Show("找不到文件Data.xml");我的XML看起来像:20120727220230+0200Freehold你正在遍历FieldData节点,而你只有一个。迭代它的子节点:foreach(XmlNodenodeindataNodes){foreach(XmlNodechildNodeinnode.ChildNodes){对于这种事情,我通常更喜欢Linq-To-Xml:vardoc=XDocument.Load("XMLFile1.xml");foreach(varchildindoc.Element("FieldData").Elements()){Console.WriteLine(child.Name);}或者你使用递归:publicvoidfindAllNodes(XmlNodenode){Console.WriteLine(node.Name);foreach(XmlNodeninnode.ChildNodes)findAllNodes(n);你把有效载荷放在哪里取决于你想使用什么类型的搜索(例如广度优先搜索,深度优先搜索等;见http://en.wikipedia.org/wiki/Euler_tour_technique)你可以这样做:XDocumentdoc=XDocument.Load(@"Data.xml");TagContents[]ArrayNode=doc.Root.Elements().Select(el=>newTagContents(){TagName=el.Name.ToString(),TagValue=el.Value}).ToArray();刚看到@Waynes的回答,效果很好。我使用以下代码进一步推进我的xml中的子节点foreach(varchildindoc.Element("rootnodename").Element("nextchildnode").Elements()){//在这里工作,probsasyncdownloadxml要在本地磁盘上归档的内容}publicvoidValidateXml(string[]Arrays){foreach(variteminArrays){Xdoc.Load(item);XmlNodeListxnList=Xdoc.SelectNodes("FirstParentNode");if(xnList.Count>0){foreach(XmlNodexninxnList){XmlNodeListanode=xn.SelectNodes("SecondParentNode");如果(anode.Count>0){foreach(anode中的XmlNodebnode){stringInnerNodeOne=bnode[“InnerNode1”]。内文;字符串InnerNodeTwo=bnode["InnerNode1"].InnerText;}}else{ErrorLog("父节点不存在");}}}else{ErrorLog("父节点不存在");}}//然后在数据库中插入或更新这些值在这里如果有人和我有同样的需求,我是这样实现的:以上是C#学习教程:如何遍历XML文件中的每个子节点?如果分享的内容对你有用,需要了解更多C#学习教程,希望你多多关注publicstringReadAllNodes(XmlNodenode){if(node.ChildNodes.Count>0){foreach(XmlNodesubNodeinnode){//递归ReadAllNodes(subNode);}}else//获取节点值。{finalText=finalText+node.InnerText+System.Environment.NewLine;}返回最终文本;}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:

最新推荐
猜你喜欢