views:

94

answers:

3

I have the following piece of XML:

<xml>
   <ObsCont xCampo="field1">
      <xTexto>example1</xTexto>
   </ObsCont>
   <ObsCont xCampo="field2">
      <xTexto>example2</xTexto>
   </ObsCont>
   <ObsCont xCampo="field3">
      <xTexto>example3</xTexto>
   </ObsCont>
</xml>

How do I (using linq) get for example what is inside the xTexto tag that has as parent the ObsCont with the xCampo attribute "field2" ?

(c#, vb.net, your choice)

+2  A: 
XDocument xml = XDocument.Parse(@"<your XML>");
from field in xml.Elements("ObsCont")
where field.Attribute("xCampo") != null && 
field.Attribute("xCampo").Value == "field2"
select field.Element("xTexto").Value;

This returns an IEnumerable of type string containing all of the values with the criteria that you specified.

Brett Widmeier
What about the xCampo part?
Mark Byers
Must have missed that part somehow...
Brett Widmeier
+1  A: 

I would use Linq to XML:

XDocument doc = XDocument.Load("input.xml");
XElement element = doc
    .Descendants("ObsCont")
    .Single(x => x.Attribute("xCampo").Value == "field2");
Console.WriteLine(element.Value);
Mark Byers
+1  A: 
    string s = @"<xml>
       <ObsCont xCampo=""field1"">
          <xTexto>example1</xTexto>
       </ObsCont>
       <ObsCont xCampo=""field2"">
          <xTexto>example2</xTexto>
       </ObsCont>
       <ObsCont xCampo=""field3"">
          <xTexto>example3</xTexto>
       </ObsCont>
    </xml>";

    XElement xe = XElement.Parse(s);
   var n1 =  xe.Elements("ObsCont")
       .Where(a => a.Attribute("xCampo") != null && 
           a.Attribute("xCampo").Value == "field2")
       .Select(a => a).SingleOrDefault();
   if (n1 != null)
   {
       var n2 = n1.Descendants("xTexto").SingleOrDefault();
       Console.Write(n2.Value);
   }
Raj Kaimal