2012-08-16 23 views
5

私の<Imovel>タグを読む必要があります。問題は私のXMLファイルに1つ以上(1つ)<Imovel>というタグがあり、各<Imovel>タグの違いIDと呼ばれる属性です。各特定のノードのすべてのXML子ノードを読む

これは、例えば

<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>タグで行う各検証の終わりに私は別の検証を行う必要があります。

だから、私は、私は私のサンプル非常によくLINQについての理解が、従わない2(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; 
    } 
} 

しかし、非常に動作しません。私の<Picture>タグのため、私のforeachステートメントでは、親タグにID属性がありません。

誰かがこの方法をお手伝いできますか?

+0

を含めてください 'しかし、私のforeach statement.'にあなたはこれで何を意味するかを説明することができ、非常にうまく動作しないのですか? –

+0

はい、私の ''タグの親にはID属性がありません –

答えて

7

次の2つの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; 
関連する問題