Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
350 views
Welcome To Ask or Share your Answers For Others

1 Answer

Instead of writing:

nodes.Elements("Foo")

write:

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).

[EDIT] Adding solution for XPath

For XPath, instead of writing:

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

you can use local-name() function:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...