Read the entire node s XML file for each specific node

I need to read all the tags of Child Nodesmy tag <Imovel>, the problem is that in my XML file I have more than one (one) tag <Imovel>, and the difference between each tag is <Imovel>an attribute with the name ID.

That's 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 to read all the tags of each tag <Imovel>, and at the end of each check that I perform in the tag <Imovel>, I need to do another check.

So, I need to do 2 (two) foreachor forand foreach, I do not understand very well LINQ, but I follow an example

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 it does not work very well, in my instruction foreach, because my tag <Picture>, its parent tag does not have an identifier attribute.

Can anyone help me make this method?

+5
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.
  }
}
+7

. 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;
+1

All Articles