Tuesday, January 6, 2009

XML Literals with namespaces

I love Xml literals in VB. They're pretty slick. However, I ran into a little gotcha today... All I wanted to do was query some data from an xml that happened to be part of a Word 2007 template (a .dotm file). It looked like I had the right query syntax, but I wasn't getting any result.

Most of the examples I found on the web were searching through xml like this:
Dim document = <customers>
<customer firstname="John"></customer>
<customer firstname="Juliet"></customer>
</customers>

Dim firstNames = From customer In document.<customers>.<customer> _
Select customer.@firstName

This works like a champ. firstNames contains what you would expect:
{Length=2}
(0): "John"
(1): "Juliet"

But let's say our xml is part of a namespace (much more realistic)

Dim document = <customers xmlns="http://fowlcoder.blogspot.com/xmlLiteralExample">
<customer firstname="John"></customer>
<customer firstname="Juliet"></customer>
</customers>
If we use the same query code as above, we don't get any results. We actually have to add some code to make the query aware of the namespace. It's pretty straightforward.

First, add an Imports statement at the beginning of the file:
Imports <xmlns:fc="http://fowlcoder.blogspot.com/xmlLiteralExample">
Now, you have to alter the query a little bit:

Dim firstNames = From customer In document.<fc:customers>.<fc:customer> _
Select customer.@firstName

Voila! You get the results that you would expect (John and Juliet).