Using a namespace with LINQ to XML

Posted Friday, August 29, 2008 3:29 PM by CoreyRoth

If you are using LINQ to XML, sooner or later, you will need to work with XML documents that don't use the namespace.  For example, you might be working with the XML from an InfoPath form and you want to get the value of a particular element.  InfoPath uses the my namespace, and you can't just specify it directly in the string (i.e.: Root.Elements("my:Group2") will not work).  To resolve this, we create a XNamespace object and pass it the URI to the namespace.

XNamespace myNamespace = "";

Once you declare the XNamespace, it's just a matter of including it before any elements or attributes you might use.

var transmittalCollection = from transmittalNode in formDocument.Root.Descendants(myNamespace + "group2")

                            select new Transmittal


                                MyNode = transmittalNode.Elements(myNamespace + "MyNode").Any() ? transmittalNode.Element(myNamespace + "MyNode").Value : null,


That's all there is to it.  I have found it very useful when I want to query data out of an InfoPath form.  I just submit the data to a service and then I use LINQ to XML to parse out the values I need.  It is much easier for me than using XPath.

Filed under: ,


No Comments

Leave a Comment