2012-08-16 1 views
5

각각의 특정 노드의 모든 XML 자식 노드 읽기 ID라는 속성입니다. 내 모든 <code><Imovel></code> 태그의 <code>Child Nodes</code>이 문제는 내가 이상 1 (하나) <code><Imovel></code> 내 XML 파일에 태그 및 각 <code><Imovel></code> 태그 사이의 차이를 가지고 있다는 것입니다 읽을 필요가

내가 각 <Imovel> 태그의 모든 태그를 읽을 필요 예

<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> 태그에 할 각 검증의 말에 나는 또 다른 유효성 검사를 할 필요가있다.

그래서, 나는, 내 샘플 잘 LINQ에 대한 이해하지만 따르지 2 (두) foreach 또는 forforeach을 할 필요가 있다고 생각

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.'에서 매우 잘 작동하지 않습니다를 포함하십시오? –

+0

네, 제 ''태그의 부모가 ID 속성을 가지고 있지 않기 때문입니다 –

답변

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;