in

Dot Net Mafia

Group site for developer blogs dealing with (usually) .NET, SharePoint 2013, SharePoint 2010, Office 365, SharePoint Online, and other Microsoft products, as well as some discussion of general programming related concepts.

This Blog

Syndication

Archives

Corey Roth [MVP]

A SharePoint MVP bringing you the latest time saving tips for SharePoint 2013, SharePoint 2010, Office 365, SharePoint Online, MOSS 2007, ASP.NET, LINQ, and Visual Studio 2012.

Using a namespace with LINQ to XML

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 = "http://schemas.microsoft.com/office/infopath/2003/myXSD/2008-02-15T09:18:32";

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.

Comments

No Comments

Leave a Comment

(required)  
(optional)
(required)  
Add

About CoreyRoth

Corey Roth is an Applications Architect at Infusion specializing in ECM and Search.
2012 dotnetmafia.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems