
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.
Popularity: 8% [?]

Recent Comments