XPATHS 和默认命名空间 [英] XPATHS and Default Namespaces
问题描述
XPath 背后的故事和对命名空间的支持是什么?XPath 作为规范是否先于名称空间?如果我有一个文档,其中元素被赋予了默认命名空间:
What is the story behind XPath and support for namespaces? Did XPath as a specification precede namespaces? If I have a document where elements have been given a default namespace:
<foo xmlns="uri" />
看起来好像有些 XPath 处理器库无法识别 //foo
因为命名空间,而另一些则可以.我的团队考虑的选项是使用正则表达式向 XPath 添加命名空间前缀(您可以通过 XmlNameTable 添加命名空间前缀),但这似乎很脆弱,因为 XPath 在节点测试方面是一种非常灵活的语言.
It appears as though some of the XPath processor libraries won't recognize //foo
because of the namespace whereas others will. The option my team has thought about is to add a namespace prefix using regular expressions to the XPath (you can add a namespace prefix via XmlNameTable) but this seems brittle since XPath is such a flexible language when it comes to node tests.
是否有适用于此的标准?
Is there a standard that applies to this?
我的方法有点笨拙,但似乎工作正常;我使用搜索/替换删除了 xmlns
声明,然后应用 XPath.
My approach is a bit hackish but it seems to work fine; I remove the xmlns
declaration with a search/replace and then apply XPath.
string readyForXpath = Regex.Replace(xmldocument, "xmlns=".+"", String.Empty );
这是一种公平的方法还是有人以不同的方式解决了这个问题?
Is that a fair approach or has anyone solved this differently?
推荐答案
我尝试了与 Palehorse 提议的类似的方法,但无法使其正常工作.由于我从已发布的服务中获取数据,因此无法更改 xml.我最终像这样使用 XmlDocument 和 XmlNamespaceManager:
I tried something similar to what palehorse proposed and could not get it to work. Since I was getting data from a published service I couldn't change the xml. I ended up using XmlDocument and XmlNamespaceManager like so:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlWithBogusNamespace);
XmlNamespaceManager nSpace = new XmlNamespaceManager(doc.NameTable);
nSpace.AddNamespace("myNs", "http://theirUri");
XmlNodeList nodes = doc.SelectNodes("//myNs:NodesIWant",nSpace);
//etc
这篇关于XPATHS 和默认命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!