开发者

XElement.Descendants doesn't work with namespace

I have a simple XML,

<S xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><开发者_如何学PythonH></H></S>

I want to find all "H" nodes.

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)
{
}

But this code doesn't work. When I remove the namespace from S tag, the code works correctly.


Your element has a namespace because xmlns effectively sets the default namespace for that element and its descendants. Try this instead:

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

Note that Descendants will never return null, so the condition at the end of your code is pointless.

If you want to find all H elements regardless of namespace, you could use:

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


Just wanted to add to Jon's answer that you can get the namespace like this:

XNamespace ns = x.Name.Namespace

Then just use it like he proposed:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜