开发者

Getting a certain node using DataSet

I have the following XML

<xml>
   <ObsCont xCampo="field1">
      <xTexto>example1</xTexto>
   </ObsCont>
   <ObsC开发者_StackOverflowont 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.


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)


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜