The little ‘gotcha’ in LINQ to XML

Gotcha in LINQ to XML

I have been working with LINQ to XML for the last couple days working on importing some XML data into a database.

I have used LINQ before with very little effort which is why I decided to give it another go for this project.

I got my program all fleshed out and started writing the LINQ query. The XML file was very simple just a root element with a collection of children.

<root>
	<child />
	<child />
	<child />
	<child />
</root>

So when my query kept returning 0 elements I started to get frustrated. Why wasn’t it working? I pulled up the past project I had done using LINQ and compared the queries. They were identical from a syntax standpoint except the new query wasn’t returning anything.

After a few short Google searches I discovered it was because the new query was reading an XML file that was using namespaces.

<root xmlns="http://namespace.uri">
	<x:child xmlns:x="http://x.namespace.uri"/>
	<x:child />
	<x:child />
	<x:child />
</root>

In this case I was able to remove the namespaces as they were not needed and had been automatically add when I downloaded the file from SharePoint.

After removing the namespaces the query worked beautifully as I had originally expected it to.

The long and short of this is watch out for namespaces when you are writing queries for LINQ to XML.

I didn’t take the time to find a solution that left the namespaces in place because I didn’t really have the time to waste if it wasn’t necessary. If anyone can provide some advice or a solution I would appreciate it. Thanks.

2 comments on this post

Lee says:
Oct 16, 2008 - 08:10:37

Hi, i had the same problem and the namespace tripped me at first. However after a bit of researching the solution was quite simple. First set your namespace.

XNamespace ns = “http://namespace.uri”;

Now before the the element name add “ns + ” e.g. new XElement(ns + “root”).

Hope this helps.

Justin says:
Oct 16, 2008 - 09:10:10

Thanks Lee, you can probably tell I don’t use LINQ much. I will keep this in mind for next time.