【问题标题】:Read all XML child nodes of each specific node读取每个特定节点的所有 XML 子节点
【发布时间】:2012-08-16 19:08:48
【问题描述】:

我需要阅读我的<Imovel>标签的所有Child Nodes,问题是我的XML文件中有不止1(一个)<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>

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

所以,我认为我需要做 2(两个)foreachforforeach,我不太了解 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语句中因为我的&lt;Picture&gt;标签,她的父标签没有ID属性。

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

【问题讨论】:

  • But doesn't work very well, in my foreach statement. 你能解释一下你的意思吗?
  • 是的,这是因为我的 &lt;Picture&gt; 标签的父级没有 ID 属性

标签: c# linq


【解决方案1】:

您应该能够使用两个 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.
  }
}

【讨论】:

    【解决方案2】:

    试试这个。 System.Xml.XPath 将向 XElement 添加 xpath 选择器。使用 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-22
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多