我该如何选择使用默认命名空间节点? [英] How do I select nodes that use a default namespace?
问题描述
XML文件的结构或多或少如下:
< XML版本=1.0编码=UTF-8>?;
< A的xmlns:XSI =http://www.w3.org/2001/XMLSchema-instance的xmlns =为url1XSI:的schemaLocation =URL2 URL3>
< B>
< C>< / c取代;
< C>< / c取代;
< C>< / c取代;
< / B>
< / A>
我的目标是选择所有C元素,但下面的XPath表达式将无法正常工作:// A / b / C
如:
XmlDocument的DOC =新的XmlDocument();
doc.Load(文件路径);
XmlNodeList中L = doc.SelectNodes(// A / B / C); // 0节点
我测试了一下工作的唯一的XPath表达式/ *(1个节点)和/ / *(所有节点)。
时的有关XML命名空间这个问题? ?如果是这样,什么是建立XMLDocument对象的正确方法
XmlDocument的DOC =新的XmlDocument();
doc.Load(文件路径);
的XmlNamespaceManager M =新的XmlNamespaceManager(doc.NameTable);
m.AddNamespace(/ *发生的事情在这里* /?);
XmlNodeList中L = doc.SelectNodes(// A / B / C,M);
您需要分配为默认命名空间的命名空间前缀正在使用,然后将文档使用,在你的XPath:
XmlDocument的DOC =新的XmlDocument();
doc.Load(文件路径);
的XmlNamespaceManager M =新的XmlNamespaceManager(doc.NameTable);
m.AddNamespace(myns名字,URL1);
XmlNodeList中L = doc.SelectNodes(/ myns名字:A / myns名字:B / myns名字:C,M);
您可以替换前缀myns名字有本质上任何东西(字母数字无空格),只要它是4号线中的XPath,之间,它的正确地分配给在第4行的为url1命名空间是一致的。
The structure of the XML file is more or less as follows:
<?xml version="1.0" encoding="UTF-8"?>
<a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="url1" xsi:schemaLocation="url2 url3">
<b>
<c></c>
<c></c>
<c></c>
</b>
</a>
My goal is to select all the "c" elements, but the following xpath expression won't work: "//a/b/c".
ie:
XmlDocument doc= new XmlDocument();
doc.Load(filepath);
XmlNodeList l = doc.SelectNodes("//a/b/c"); // 0 nodes
The only xpath expressions I tested that worked are /* (1 node) and //* (all nodes).
Is this problem related to the XML namespace? If so, what's the proper way to set up the XMLDocument object?
XmlDocument doc= new XmlDocument();
doc.Load(filepath);
XmlNamespaceManager m = new XmlNamespaceManager(doc.NameTable);
m.AddNamespace(/* what goes here? */);
XmlNodeList l = doc.SelectNodes("//a/b/c", m);
You need to assign a namespace prefix for the default namespace that the document is using, and then use that in your XPath:
XmlDocument doc= new XmlDocument();
doc.Load(filepath);
XmlNamespaceManager m = new XmlNamespaceManager(doc.NameTable);
m.AddNamespace("myns", "url1");
XmlNodeList l = doc.SelectNodes("/myns:a/myns:b/myns:c", m);
You can replace the prefix "myns" with essentially anything (alphanumeric without spaces), as long as it's consistent between line 4 and the XPath, and that it's correctly assigned to the "url1" namespace in line 4.
这篇关于我该如何选择使用默认命名空间节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!