Marcelo
Marcelo

Reputation: 3391

Getting a certain node using DataSet

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.

Upvotes: 0

Views: 1453

Answers (3)

John M Gant
John M Gant

Reputation: 19308

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

Upvotes: 0

Chris Haas
Chris Haas

Reputation: 55427

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)

Upvotes: 1

Anthony Pegram
Anthony Pegram

Reputation: 126884

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

Upvotes: 1

Related Questions