What is wrong in my XPath?
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?
/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"
精彩评论