問題描述
XML文件的結(jié)構(gòu)大致如下:
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>
我的目標(biāo)是選擇所有c"元素,但以下 xpath 表達(dá)式不起作用://a/b/c".
My goal is to select all the "c" elements, but the following xpath expression won't work: "http://a/b/c".
即:
XmlDocument doc= new XmlDocument();
doc.Load(filepath);
XmlNodeList l = doc.SelectNodes("http://a/b/c"); // 0 nodes
我測試過的唯一有效的 xpath 表達(dá)式是/*(1 個節(jié)點)和//*(所有節(jié)點).
The only xpath expressions I tested that worked are /* (1 node) and //* (all nodes).
這個問題與 XML 命名空間有關(guān)嗎?如果是這樣,設(shè)置 XMLDocument 對象的正確方法是什么?
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("http://a/b/c", m);
推薦答案
你需要為文檔使用的默認(rèn)命名空間分配一個命名空間前綴,然后在你的 XPath 中使用它:
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);
您可以將前綴myns"替換為基本上任何內(nèi)容(不帶空格的字母數(shù)字),只要它在第 4 行和 XPath 之間保持一致,并且正確分配給第 4 行中的url1"命名空間.
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.
這篇關(guān)于如何選擇使用默認(rèn)命名空間的節(jié)點?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!