使用 XPath 按 Id 选择 XMLNode [英] Select XMLNode by Id using XPath
问题描述
我有以下 XML 片段,请注意 Reference 节点包含一个链接到 Body 节点的 Id 属性的 URI.
I have the below fragement of XML, notice that the Reference node holds a URI which links to the Id attribute of the Body node.
<Reference URI="#Body">
<SOAP-ENV:Body Id="Body" xmlns:SOAP-ENV="http://www.dingo.org">
<ns0:Add xmlns:ns0="http://www.moo.com">
<ns0:a>2</ns0:a>
<ns0:b>3</ns0:b>
</ns0:Add>
</SOAP-ENV:Body>
如果我有 URI 属性的值,我将如何获得整个 Body XMLNode?我认为这最好通过 XPath 表达来完成,但对 XPath 没有任何线索.请注意,XML 并不总是那么简单.我在 c# 中这样做 顺便说一句 :)
If I had the value of the URI attribute how would I then get the whole Body XMLNode? I presume this would be best done via an XPath epression but haven't any clue on XPath. Note that the XML will not always be so simple. I'm doing this in c# btw :)
有什么想法吗?
谢谢
乔恩
我事先不知道 XML 结构或命名空间,我只知道引用元素具有我想要检索的 xmlNode 的 ID,希望这能更清楚一些.
I wouldn't know the XML structure or namespaces before hand, all I would know is that the reference element has the ID of the xmlNode i want to retrieve, hope this is sligtly clearer.
推荐答案
您可以向 XPath 表达式的任何步骤添加适用于相对(或绝对节点)的条件.
You can add a condition that applies to a relative (or absolute node) to any step of an XPath expression.
在这种情况下:
//*[@id=substring-after(/Reference/@URI, '#')]
//*
匹配文档中的所有元素.[]
中的部分是条件.在条件内部,采用根 References 节点的 URI 元素部分,但忽略#"(以及它之前的任何内容).
The //*
matches all elements in the document. The part in []
is a condition. Inside the condition the part of the URI element of the root References node is taken, but ignoring the '#' (and anything before it).
示例代码,假设您已将 XML 加载到 XPathDocument
doc
:
Sample code, assuming you have loaded your XML into XPathDocument
doc
:
var nav = doc.CreateNavigator();
var found = nav.SelectSingleNode("//*[@id=substring-after(/Reference/@URI, '#')]");
这篇关于使用 XPath 按 Id 选择 XMLNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!