【问题标题】:XElement.Descendants doesn't work with namespaceXElement.Descendants 不适用于命名空间
【发布时间】:2011-08-29 07:16:54
【问题描述】:

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

【问题讨论】:

  • 这个问题与WPF无关,顺便说一句...

标签: namespaces xelement


【解决方案1】:

您的元素有一个命名空间,因为xmlns 有效地为该元素及其后代设置了 default 命名空间。试试这个:

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

请注意,Descendants从不返回 null,因此代码末尾的条件毫无意义。

如果你想找到 all H 元素而不考虑命名空间,你可以使用:

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

【讨论】:

    【解决方案2】:

    只是想补充一下 Jon 的答案,您可以像这样获得命名空间:

    XNamespace ns = x.Name.Namespace
    

    那就按照他的建议使用吧:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-24
      • 1970-01-01
      • 1970-01-01
      • 2018-11-17
      • 1970-01-01
      • 2012-09-16
      • 2014-07-11
      相关资源
      最近更新 更多