我的 XPath 出了什么问题?

发布于 2024-08-19 12:39:44 字数 723 浏览 4 评论 0原文

这里我有 xml:,

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

我想通过提取元素来了解 «car» 的 «type»。我想这样的事情:

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

就足够了,但是当我尝试执行我的 C# 代码时:

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

对象 «node» 它始终包含第一个子元素 «field» (报价),并且在 SelectNodes("... 相同xpath ...") 返回所有元素 «field» 忽略条件。

有什么问题吗? 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一抹淡然 2024-08-26 12:39:45
/root/field[text()='car']/@type

将返回一个表示元素“field”的属性“type”的节点,其文本值为“car”。此 XmlNode 的值将为“ferrari”。

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

将返回一个表示元素“field”(其文本值为“car”)的节点,您可以通过编程方式从 type 属性获取该节点:

XmlNode fieldNode = document.DocumentElement.SelectSingleNode(@"/root/field[text()='car']");
string type = fieldNode.Attributes["type"].Value;
//type == "ferrari"
/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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文