Read all XML child nodes of each specific node

Viewed 11391

I need to read all the Child Nodes of my <Imovel> tag, the problem is that I has more than 1 (one) <Imovel> tag in my XML file, and the difference between each <Imovel> tag is an attribute called ID.

This is an example

<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>

I need read all tags of each <Imovel> tag, and in the end of each validation that I do in my <Imovel> tag I need to do another validation.

So, I think I need to do 2 (two) foreach or a for and a foreach, I don't understand very well about LINQ but follow my sample

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;
    }
}

But doesn't work very well, in my foreach statement because my <Picture> tag, her parent tag don't has an ID attribute.

Somebody can help me to do this method ?

2 Answers
Related