Default namespace for LINQ to XML query

Linq rocks completely, however when you write queries against XML documents that have namespaces (and most likely the document will only have one namespace) you have to specify them in your queries. Here’s a nice solution from mike a moogly.me.uk – just strip all of the useless namespaces from XDocument object and query away!

public void RemoveNamespace(XDocument xdoc)

{

foreach (XElement e in xdoc.Root.DescendantsAndSelf())

{

if (e.Name.Namespace != XNamespace.None)

{

e.Name = XNamespace.None.GetName(e.Name.LocalName);

}

if (e.Attributes().Where(a => a.IsNamespaceDeclaration || a.Name.Namespace != XNamespace.None).Any())

{

e.ReplaceAttributes(e.Attributes().Select(a => a.IsNamespaceDeclaration ? null : a.Name.Namespace != XNamespace.None ? new XAttribute(XNamespace.None.GetName(a.Name.LocalName), a.Value) : a));

}

}

}

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *