在任意深度选择通过XPath的XML节点 [英] Select an XML node via XPath at an arbitrary depth

查看:218
本文介绍了在任意深度选择通过XPath的XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个XML文件,我想要得到的第一个节点具有一定的名字,无论在哪个嵌套深度被遏制。

Having an XML document, I want to get the first node with a certain name, no matter in which nesting depth it is contained.

我试过几件事情,而不成功:

I tried several things without success:

var node1 = doc.SelectSingleNode(@"//Shortcut");
var node2 = doc.SelectSingleNode(@"/*/Shortcut");
var node3 = doc.SelectSingleNode(@"//*/Shortcut");
var node4 = doc.SelectSingleNode(@"*/Shortcut");
...

每个通话效果在 NULL 节点。

我觉得应该是一些琐碎的XPath语法。 ?你能帮助我。

I think it should be some trivial XPath syntax. Can you help me?

(如果这事项:XML文档是一个的维克斯项目,所以有可能是一些涉及空间的问题?!​​?)。

(In case this matters: The XML document is an input file for a WiX project, so there could be some namespace issues involved?!?).

修改

我也试过以下内容:

var nsm = new XmlNamespaceManager(doc.NameTable);
nsm.AddNamespace(string.Empty, @"http://schemas.microsoft.com/wix/2006/wi");
nsm.AddNamespace(@"ns", @"http://schemas.microsoft.com/wix/2006/wi");



连同

together with:

var node1 = doc.SelectSingleNode(@"//Shortcut", nsm);
var node2 = doc.SelectSingleNode(@"/*/Shortcut", nsm);
var node3 = doc.SelectSingleNode(@"//*/Shortcut", nsm);
var node4 = doc.SelectSingleNode(@"*/Shortcut", nsm);
...



通往相同的结果。

Leading to the same results.

修改2 - 解决方案

我找到了解决办法:

var nsm = new XmlNamespaceManager(doc.NameTable);
nsm.AddNamespace(string.Empty, @"http://schemas.microsoft.com/wix/2006/wi");
nsm.AddNamespace(@"ns", @"http://schemas.microsoft.com/wix/2006/wi");



然后

and then

var node1 = doc.SelectSingleNode(@"//ns:Shortcut", nsm);

这成功了。

推荐答案

的选择正是通缉的节点(并没有什么附加)XPath表达式是

(//x:Shortcut)[1]

因此,使用:

doc.SelectNodes("(//x:Shortcut)[1]", someNamespaceManager)

其中,

前缀×绑定到命名空间http://schemas.microsoft.com/wix/2006/wi

someNamespaceManager

这已超过建议的解决方案的优势(使用的SelectSingleNode()),因为它可以很容易地调整选择了N次想XML文档中的节点

This has an advantage over the proposed solution (to use SelectSingleNode()), because it can easily be adjusted to select the N-th wanted node in the XML document.

例如:

   (//x:Shortcut)[3]

选择3日(按文档顺序) X:快捷方式元素,以及

selects the 3rd (in document order) x:Shortcut element, and

   (//x:Shortcut)[last()]

选择最后一个(按文档顺序) X:。快捷方式元素的XML文档中的

selects the last (in document order) x:Shortcut element in the XML document.

这篇关于在任意深度选择通过XPath的XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆