忽略LINQ to XML中的名称空间

Jon*_*len 83 .net xml linq

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

我问,因为命名空间是以半随机方式设置的,我厌倦了必须搜索带有和没有命名空间的节点.

Pav*_*aev 134

而不是写:

nodes.Elements("Foo")
Run Code Online (Sandbox Code Playgroud)

写:

nodes.Elements().Where(e => e.Name.LocalName == "Foo")
Run Code Online (Sandbox Code Playgroud)

当你厌倦了它,制作自己的扩展方法:

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

如果你必须经常处理命名空间属性(这是相对罕见的),那么同样适用于属性.

[编辑]为XPath添加解决方案

对于XPath,而不是写:

/foo/bar | /foo/ns:bar | /ns:foo/bar | /ns:foo/ns:bar
Run Code Online (Sandbox Code Playgroud)

你可以使用local-name()功能:

/*[local-name() = 'foo']/*[local-name() = 'bar']
Run Code Online (Sandbox Code Playgroud)


Ahm*_*eed 15

这是一个删除命名空间的方法:

private static XElement StripNamespaces(XElement rootElement)
{
    foreach (var element in rootElement.DescendantsAndSelf())
    {
        // update element name if a namespace is available
        if (element.Name.Namespace != XNamespace.None)
        {
            element.Name = XNamespace.None.GetName(element.Name.LocalName);
        }

        // check if the element contains attributes with defined namespaces (ignore xml and empty namespaces)
        bool hasDefinedNamespaces = element.Attributes().Any(attribute => attribute.IsNamespaceDeclaration ||
                (attribute.Name.Namespace != XNamespace.None && attribute.Name.Namespace != XNamespace.Xml));

        if (hasDefinedNamespaces)
        {
            // ignore attributes with a namespace declaration
            // strip namespace from attributes with defined namespaces, ignore xml / empty namespaces
            // xml namespace is ignored to retain the space preserve attribute
            var attributes = element.Attributes()
                                    .Where(attribute => !attribute.IsNamespaceDeclaration)
                                    .Select(attribute =>
                                        (attribute.Name.Namespace != XNamespace.None && attribute.Name.Namespace != XNamespace.Xml) ?
                                            new XAttribute(XNamespace.None.GetName(attribute.Name.LocalName), attribute.Value) :
                                            attribute
                                    );

            // replace with attributes result
            element.ReplaceAttributes(attributes);
        }
    }
    return rootElement;
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

XNamespace ns = "http://schemas.domain.com/orders";
XElement xml =
    new XElement(ns + "order",
        new XElement(ns + "customer", "Foo", new XAttribute("hello", "world")),
        new XElement("purchases",
            new XElement(ns + "purchase", "Unicycle", new XAttribute("price", "100.00")),
            new XElement("purchase", "Bicycle"),
            new XElement(ns + "purchase", "Tricycle",
                new XAttribute("price", "300.00"),
                new XAttribute(XNamespace.Xml.GetName("space"), "preserve")
            )
        )
    );

Console.WriteLine(xml.Element("customer") == null);
Console.WriteLine(xml);
StripNamespaces(xml);
Console.WriteLine(xml);
Console.WriteLine(xml.Element("customer").Attribute("hello").Value);
Run Code Online (Sandbox Code Playgroud)