开发者

What is wrong in my XPath?

开发者 https://www.devze.com 2022-12-18 02:05 出处:网络
Here I have the xml: <root> <field ...>offer</field> <field type=\"ferrari\" ...>car</field>

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"
0

精彩评论

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