读取每个特定节点的所有XML子节点

我需要读取标签的所有Child Nodes ,问题是我的XML文件中有超过1(一)个标签,每个标签之间的区别是一个名为ID的属性。

这是一个例子

   2012-01-01 00:00:00.000   hhhhh   // Here comes a lot of another tags   2012-01-01 00:00:00.000   tttt   // Here comes a lot of another tags   

我需要读取每个标签的所有标签,并且在我在标签中进行的每次validation结束时,我需要进行另一次validation。

所以,我认为我需要做2(2)个foreach或者forforeach ,我对LINQ不是很了解但是关注我的样本

 XmlReader rdr = XmlReader.Create(file); XDocument doc2 = XDocument.Load(rdr); ValidaCampos valida = new ValidaCampos(); //// Here I Count the number of `` tags exist in my XML File for (int i = 1; i  x.Name == "Imovel").Count(); i++) { //// Get the ID attribute that exist in my `` tag id = doc2.Root.Descendants().ElementAt(0).Attribute("id").Value; foreach (var element in doc2.Root.Descendants().Where(x => x.Parent.Attribute("id").Value == id)) { String name = element.Name.LocalName; String value = element.Value; } } 

但是效果不好,在我的foreach语句中因为我的标签,她的父标签没有ID属性。

有人可以帮我做这个方法吗?

您应该能够使用两个foreach语句执行此操作:

 foreach(var imovel in doc2.Root.Descendants("Imovel")) { //Do something with the Imovel node foreach(var children in imovel.Descendants()) { //Do something with the child nodes of Imovel. } } 

试试这个。 System.Xml.XPath将xpath选择器添加到XElement。 使用xpath查找元素更快更简单。

您不需要XmlReader和XDocument来加载文件。

 XElement root = XElement.Load("test.xml"); foreach (XElement imovel in root.XPathSelectElements("//Imovel")) { foreach (var children in imovel.Descendants()) { String name = children.Name.LocalName; String value = children.Value; Console.WriteLine("Name:{0}, Value:{1}", name, value); } //use relative xpath to find a child element XElement picturePath = imovel.XPathSelectElement(".//Pictures/Picture/Path"); Console.WriteLine("Picture Path:{0}", picturePath.Value); } 

请包括

 System.Xml.XPath;