XElement.Descendants不适用于命名空间

时间:2011-08-29 07:16:54

标签: namespaces xelement

我有一个简单的XML,

<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标签中删除命名空间时,代码可以正常工作。

2 个答案:

答案 0 :(得分:45)

您的元素具有命名空间,因为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");

答案 1 :(得分:6)

只想添加Jon的答案,你可以得到这样的命名空间:

XNamespace ns = x.Name.Namespace

然后就像他提议的那样使用它:

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