閱讀

2012-08-16 37 views
5

我需要閱讀所有我的<Imovel>標籤的Child Nodes,問題是,我有我的XML文件超過1(一)<Imovel>標籤,每個<Imovel>標籤之間的區別每一個特定節點的所有XML子節點是一個稱爲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(二)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聲明中,因爲我的<Picture>標籤,她的父標籤沒有ID屬性。

有人可以幫我做這個方法嗎?

+0

'但不工作得非常好,在我的foreach statement.'你能解釋一下你這個是什麼意思? – 2012-08-16 19:11:28

+0

是的,這是我的''標記的父母沒有ID屬性 – 2012-08-16 19:13:58

回答

7

你應該能有兩個的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. 
    } 
} 
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;