2011-08-29 104 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");