忽略 LINQ to XML 中的命名空间 [英] Ignore namespaces in LINQ to XML

查看:25
本文介绍了忽略 LINQ to XML 中的命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让 LINQ to XML iqnore 所有命名空间?或者,如何去除命名空间?

How do I have LINQ to XML iqnore all namespaces? Or alteranately, how to I strip out the namespaces?

我之所以这么问是因为命名空间是以半随机的方式设置的,而且我厌倦了搜索带有和不带有命名空间的节点.

I'm asking because the namespaces are being set in a semi-random fashion and I'm tired of having to search for nodes both with and without a namespace.

推荐答案

代替写作:

nodes.Elements("Foo")

写:

nodes.Elements().Where(e => e.Name.LocalName == "Foo")

当你厌倦它时,创建你自己的扩展方法:

and when you get tired of it, make your own extension method:

public static IEnumerable<XElement> ElementsAnyNS<T>(this IEnumerable<T> source, string localName)
    where T : XContainer
{
    return source.Elements().Where(e => e.Name.LocalName == localName);
}

属性同上,如果您必须经常处理命名空间属性(这种情况相对较少).

Ditto for attributes, if you have to deal with namespaced attributes often (which is relatively rare).

对于 XPath,而不是写:

For XPath, instead of writing:

/foo/bar | /foo/ns:bar | /ns:foo/bar | /ns:foo/ns:bar

你可以使用local-name()函数:

/*[local-name() = 'foo']/*[local-name() = 'bar']

这篇关于忽略 LINQ to XML 中的命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆