我有一个XML文档,想要获取第一个具有特定名称的节点,无论它在哪个嵌套深度中。
我尝试了几种方法,但都没有成功:
var node1 = doc.SelectSingleNode(@"//Shortcut");
var node2 = doc.SelectSingleNode(@"/*/Shortcut");
var node3 = doc.SelectSingleNode(@"//*/Shortcut");
var node4 = doc.SelectSingleNode(@"*/Shortcut");
...
每次调用都会生成一个
NULL
节点。我认为这应该是一些琐碎的XPath语法。你能帮我吗?
(如果有关系的话:XML文档是WiX项目的输入文件,所以可能涉及一些命名空间问题?!)。 编辑 我也尝试了以下内容:
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");
一起:
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");
然后
var node1 = doc.SelectSingleNode(@"//ns:Shortcut", nsm);
这成功了。