views:

57

answers:

1

Hi! Here I have the xml:

<root>
    <field ...>offer</field>
    <field type="ferrari" ...>car</field>
    <field ...>company</field>
    <field ...>whatever</field>
</root>

and I want to know the «type» of the «car» by extracting the element. I thought something like this:

/root[field='car']/field (or /root[field='car'])

was enough, but when I tried to execute my C# code:

XmlDocument document = new XmlDocument();
document.InnerXml = "..."; // xml of above
XmlNode node = document.DocumentElement.SelectSingleNode("... xpath of above ...");

the object «node» it always contains the first child element «field» (the offer) and in the case of SelectNodes("... same xpath ...") returns all the elements «field» ignoring the condition.

What's the problem? The XPath is wrong?

+2  A: 
/root/field[text()='car']/@type

Will bring back a node representing the attribute "type" of the element "field" whose text value is "car". The value of this XmlNode will be "ferrari".

/root/field[text()='car']

Will bring back a node representing the element "field" (whose text value is "car"), which you could programmatically get at the type attribute:

XmlNode fieldNode = document.DocumentElement.SelectSingleNode(@"/root/field[text()='car']");
string type = fieldNode.Attributes["type"].Value;
//type == "ferrari"
Bryan Batchelder
thanks man! :) I didn't know I had to specify that the inner content must be turned to text!BR!
Alexian