2011-08-29 83 views
14

我有一個簡單的XML工作,XElement.Descendants沒有命名空間

<S xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><H></H></S> 

我想找到的所有「H」的節點。

XElement x = XElement.Parse("<S xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><H></H></S>"); 
IEnumerable<XElement> h = x.Descendants("H"); 
if (h != null) 
{ 
} 

但是這段代碼不起作用。 當我從S標籤中刪除命名空間時,代碼正常工作。

+0

這個問題與WPF無關,順便說一下... –

+0

謝謝,我刪除了「WPF」標籤。 –

回答

42

元素有一個名稱空間,因爲xmlns有效地設置該元素及其後代的默認名稱空間。試試這個:

XNamespace ns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"; 
IEnumerable<XElement> h = x.Descendants(ns + "H"); 

注意Descendants從未返回null,所以在你的代碼末端的狀況是沒有意義的。

如果你想找到所有H元素,無論命名空間,你可以使用:

var h = x.Descendants().Where(e => e.Name.LocalName == "H"); 
+0

感謝和問候。 –

6

只想添加到Jon的回答,你可以得到這樣的命名空間:

XNamespace ns = x.Name.Namespace 

然後就像他建議的那樣使用它:

IEnumerable<XElement> h = x.Descendants(ns + "H");