忽略命名空间在LINQ to XML空间、LINQ、XML、to

2023-09-02 21:24:08 作者:ゞ、手心的余温慢慢蔓延丶

我怎么会有LINQ到XML iqnore所有命名空间?或者alteranately,怎么我带出的命名空间?

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() = 'foo']/*[local-name() = 'bar']