5

我需要阅读Child Nodes我的所有<Imovel>标签,问题是我的 XML 文件中有多个(一个)<Imovel>标签,每个标签之间的区别<Imovel>是一个名为 ID 的属性。

这是一个例子

<Imoveis>
   <Imovel id="555">
      <DateImovel>2012-01-01 00:00:00.000</DateImovel>
      <Pictures>
          <Picture>
              <Path>hhhhh</Path>
          </Picture>
      </Pictures>
      // Here comes a lot of another tags
   </Imovel>
   <Imovel id="777">
      <DateImovel>2012-01-01 00:00:00.000</DateImovel>
      <Pictures>
          <Picture>
              <Path>tttt</Path>
          </Picture>
      </Pictures>
      // Here comes a lot of another tags
   </Imovel>
</Imoveis>

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

所以,我想我需要做 2 (两个)foreach或 afor和 a foreach,我不太了解,LINQ但请按照我的示例

XmlReader rdr = XmlReader.Create(file);
XDocument doc2 = XDocument.Load(rdr);
ValidaCampos valida = new ValidaCampos();

//// Here I Count the number of `<Imovel>` tags exist in my XML File                        
for (int i = 1; i <= doc2.Root.Descendants().Where(x => x.Name == "Imovel").Count(); i++)
{
    //// Get the ID attribute that exist in my `<Imovel>` 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声明中因为我的<Picture>标签,她的父标签没有 ID 属性。

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

4

2 回答 2

8

您应该可以使用两个 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.
  }
}
于 2012-08-16T19:15:54.677 回答
1

尝试这个。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;
于 2014-11-29T01:12:48.887 回答