XML is one of the most popular formats for files and data streams that need to represent complex data. The InfoPath forms use XML data as well as many task forms and the RSS data feed.
Once you’ve got your hands on XML data, you can use LINQ to query anything from the data. LINQ to XML is a great way to manipulate the XML data out of the XML file.
- The first thing we need to do is get the XML of the InfoPath form, before we can work with it. Open the file and get the XML. You can then use the File object along with OpenBinary() to get the raw bytes of the XML.byte[] xmlBytes = workflowProperties.Item.File.OpenBinary();
- You can then takes those bytes and read them into a regular string.string xmlString = System.Text.Encoding.UTF8.GetString(xmlBytes);if (xmlString[0] == (char)0xfeff)xmlString = xmlString.Substring(1);
- Now we need to get the XML string into an XDocument class so that we can query it and manipulate it. Since we have a string, we will need to create a StringReader to read it.XDocument documentsXml = XDocument.Load(new System.IO.StringReader(xmlString));
- InfoPath documents always have a namespace defined for my so we need to use the XNamespace object for any future references inside the InfoPath form.XNamespace documentNamespace = http://schemas.microsoft.com/office/infopath/2003/myXSD/2098-05-03T16:48:38;
- At this point you can start using LINQ to XML to get the data you need out of the InfoPath form. For example, if I had a field called my:FirstName at the root of the document. I could use something like the following to get the value.string firstName = documentsXml.Root.Element(documentNamespace + “FirstName”).Value;
- If you are working with other data types, you can always cast it like this.int customerId =
int.Parse(documentsXml.Root.Element(documentNamespace +
“CustomerId”).Value);
- You can use LINQ to XML to iterate through a repeating table. As another example to iterate through a repeating table called Items with an element of Item, you could do something like the following:var items = from item in
documentsXml.Root.Element(“Items”).Elements(“Item”)select item;foreach (var item in items)
{
Console.WriteLine(item.Element(“Field1”).Value);
Console.WriteLine(item.Element(“Field2”).Value);
}In this case, I use LINQ to return an IEnumberable<XElement> representing each repeating item. I can then use this in a foreach loop to print out the results.
LINQ to XML really offers a lot of flexibility to manipulate the XML data inside a form. It makes your experience with InfoPath and workflow a better one