December 2009
M T W T F S S
« Jul    
 123456
78910111213
14151617181920
21222324252627
28293031  

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

}

}

}

1 comment to Default namespace for LINQ to XML query

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>