Today, I had the opportunity to give a short introduction on how to do some basic queries on XML documents with LINQ to XML. In the talk, I talked about how to create anonymous types from your XML document so that you can work with strong types. I also showed some uses some of the classes, methods, and properties, they would use most when working with LINQ to XML.
I also discussed how LINQ to XML can be used to make working with repeating tables in InfoPath easier. Consider the following XML of an InfoPath form. We have a repeating table called RepeatingTable and in the table there is element called Item.
<?xml version="1.0" encoding="utf-8"?>
If you needed to work with this repeating table when the InfoPath form was loaded again, you could use code like the following. You could also apply a similar technique to work with this data inside a workflow.
// use the MainDataSource to read the XML of the InfoPath Form
XDocument infoPathDocument = XDocument.Load(new System.IO.StringReader(MainDataSource.CreateNavigator().OuterXml));
// required to access my: namespace
XNamespace myNamespace = "http://schemas.microsoft.com/office/infopath/2003/myXSD/2008-12-30T15:48:37";
// use descendants node to find any element with the name Item in the tree
var items = from item in infoPathDocument.Descendants(myNamespace + "Item")
Name = item.Element(myNamespace + "Name").Value,
Color = item.Element(myNamespace + "Color").Value,
Price = item.Element(myNamespace + "Price").Value
foreach (var item in items)
// do something
In the code above, I use the CreateNavigator method of the MainDataSource as usual when working with an InfoPath form and I use a StringReader to load it into an XDocument. Since InfoPath form’s always use the my namespace it is necessary to declare it using the XNamespace object and use it before referring to any element or attribute in the document. In the example above, I create a new anonymous type with the Name, Color, and Price and then I can use a foreach loop to iterate through the items.
I have attached the code for the example above as well as the other examples I mentioned in the talk to this post. Please, let me know if you have any questions.
Follow me on twitter.