views:

47

answers:

3

I have the following XML

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

Is there a way to get the content of "xTexto" inside the ObsCont that has "field2" value for the attribute xCampo using DataSet ?

It would be desireable to have a single liner like the following:

DataSet ds = new DataSet();
ds.ReadXml(StrArquivoProc);
ds.Tables["xml"].Rows[0]["field"].ToString();
//field == "information"

If I use the same method I'm not specifying that I want the one with the desired attribute.

+1  A: 

You could certainly use something like Linq to XML to load the entire document into a collection that you could further query or iterate over to use to whatever ends you desire, including binding to data controls. Or you could specifically query the document directly for the desired attribute/element value combination, like below.

XDocument document = XDocument.Parse(xml);
// or document = XDocument.Load(xmlFile)
// System.Xml.Linq namespace

var query = (from obscont in document.Descendants("ObsCont")
             where obscont.Attribute("xCampo").Value == "field2"
             select obscont.Element("xTexto").Value).First();

Console.WriteLine(query);
Anthony Pegram
Thank you, but I'm using .net 2.0, then I have no LINQ =( Is there a way to do that with dataset ?
MarceloRamires
+1  A: 

If you have an absolutely known data path then you can use XPath:

    Dim myFile = "c:\test.xml"
    Dim X As New System.Xml.XmlDocument()
    X.Load(myFile)
    Dim N = X.SelectSingleNode("//xml/ObsCont[@xCampo=""field2""]/xTexto")
    Trace.WriteLine(N.InnerText)
Chris Haas
+1 for using XML tools to process XML, although if it's read-only you might get better performance using an XPathDocument and XPathNavigator. The syntax is similar.
John M Gant
A: 

Here's the XPathDocument version of Chris Haas' solution, for what it's worth.

Dim myFile = "c:\test.xml"
Dim fs As New FileStream(myFile, FileMode.Open)
Dim doc As New XPathDocument(fs)
fs.Dispose() 
Dim nav = doc.CreateNavigator()
Dim node = nav.SelectSingleNode("//xml/ObsCont[@xCampo=""field2""]/xTexto")
Trace.WriteLine(node.Value)

Or if you have the XML in a string, use a StringReader instead.

Dim doc As New XPathDocument(New StringReader(myXml))
'And so forth...'
John M Gant