在以下程序中,helloElem
不爲空,如預期。獲取XML元素
string xml = @"<root>
<hello></hello>
</root>";
XDocument xmlDoc = XDocument.Parse(xml);
var helloElem = xmlDoc.Root.Element("hello"); //not null
如果給XML命名空間:
string xml = @"<root xmlns=""namespace"">
<hello></hello>
</root>";
XDocument xmlDoc = XDocument.Parse(xml);
var helloElem = xmlDoc.Root.Element("hello"); //null
爲什麼helloElem
成爲空?在這種情況下,我如何獲得hello元素?
這是行得通的,但是有可能使代碼支持所有的情況下,使用/不使用命名空間並且不對名稱空間進行硬編碼? –
@ roger.james這就像要求C#編譯器忽略名稱空間,並試圖在項目中查找匹配對象。就像你的項目一樣,XML中的命名空間有助於將'candy:bar'與'foo:bar'區分開來,這肯定是兩個完全不同的東西。 –