使用 C# XmlDocument 选择相对 XPath 节点 [英] Relative XPath node selection with C# XmlDocument
问题描述
想象以下 XML 文档:
Imagine the following XML document:
<root>
<person_data>
<person>
<name>John</name>
<age>35</age>
</person>
<person>
<name>Jim</name>
<age>50</age>
</person>
</person_data>
<locations>
<location>
<name>John</name>
<country>USA</country>
</location>
<location>
<name>Jim</name>
<country>Japan</country>
</location>
</locations>
</root>
然后我为 Jim 选择人员节点:
I then select the person node for Jim:
XmlNode personNode = doc.SelectSingleNode("//person[name = 'Jim']");
现在从这个带有单个 XPath 选择的节点中,我想检索 Jim 的位置节点.类似的东西:
And now from this node with a single XPath select I would like to retrieve Jim's location node. Something like:
XmlNode locationNode = personNode.SelectSingleNode("//location[name = {reference to personNode}/name]");
因为我是根据 personNode 进行选择的,所以如果我可以在选择中引用它会很方便.这可能吗?...有联系吗?
Since I am selecting based on the personNode it would be handy if I could reference it in the select. Is this possible?.. is the connection there?
当然,我可以添加一些额外的代码行并将名称放入一个变量中,然后在 XPath 字符串中使用它,但这不是我要问的.
Sure I could put in a few extra lines of code and put the name into a variable and use this in the XPath string but that is not what I am asking.
推荐答案
这不是很有效,但应该有效.文件越大,速度就越慢.
This is not very efficient, but it should work. The larger the file gets, the slower will this be.
string xpath = "//location[name = //person[name='Jim']/name]";
XmlNode locationNode = doc.SelectSingleNode(xpath);
这就是效率低下的原因:
Here is why this is inefficient:
//
"速记会导致对所有节点进行文档范围的扫描.[]
"谓词在循环中运行,对于与//person
"匹配的每个
一次.- 第二个
//
"导致再次进行文档范围的扫描,这次对每个
进行一次.
- The "
//
" shorthand causes a document-wide scan of all nodes. - The "
[]
" predicate runs in a loop, once for each<person>
matched by "//person
". - The second "
//
" causes a causes a document-wide scan again, this time once for each<person>
.
这意味着你会得到二次 O(n²) 最坏情况的性能,这很糟糕.如果您的文档中有 n 个
和 n 个
,则会发生 n x n 次文档范围扫描.完全来自一个看起来很无辜的 XPath 表达式.
This means you get quadratic O(n²) worst-case performance, which is bad. If there are n <person>
s and n <location>
s in your document, n x n document wide scans happen. All out of one innocent looking XPath expression.
我建议不要使用这种方法.两步选择(先找到人,然后是位置)效果会更好.
I'd recommend against that approach. A two-step selection (first, find the person, then the location) will perform better.
这篇关于使用 C# XmlDocument 选择相对 XPath 节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!