Monday, October 15, 2012

Get data from InfoPath form using Object Model(C#)

The InfoPath forms (.xml) files stored in the following Path
Open the site inthe SharePoint desinger, click on All Files folder and list -> Open any xml file

     <my:Organization>Financial Services</my:Organization>
     <my:Organization>IT Department</my:Organization>

use the below code:

SPFile file = properties.ListItem.File;
           if (file == null)
           // Get the binary data of the file
           byte[] xmlFormData = null;
           xmlFormData = file.OpenBinary();

           // Load the data into an XPathDocument object
           XPathDocument ipForm = null;
           if (xmlFormData != null)
               using (MemoryStream ms = new MemoryStream(xmlFormData))
                   ipForm = new XPathDocument(ms);
           if (ipForm == null)
           // Create an XPathNavigator object to navigate the XML
           XPathNavigator ipFormNav = ipForm.CreateNavigator();
           XmlNamespaceManager nsManager =
           new XmlNamespaceManager(new NameTable());
           foreach (KeyValuePair<string, string> ns in ipFormNav.GetNamespacesInScope(XmlNamespaceScope.All))
               if (ns.Key == String.Empty)
                   nsManager.AddNamespace("def", ns.Value);
                   nsManager.AddNamespace(ns.Key, ns.Value);
           // Retrieve the value of the field in the InfoPath form
           //XPathNavigator nodeNav = ipFormNav.SelectSingleNode("//my:DisplayName", nsManager);
           XPathNodeIterator rows = ipFormNav.Select("//my:group7/my:group8", nsManager);
           string _Attendees = "";
           string _Organization = "";
           DataTable table = new DataTable();
           table.Columns.Add("List of Attendees", typeof(string));
           table.Columns.Add("Organization", typeof(string));
           while (rows.MoveNext())
               _Attendees=rows.Current.SelectSingleNode("my:ListOfAttendee", nsManager).Value;
               _Organization = rows.Current.SelectSingleNode("my:Organization", nsManager).Value;
               table.Rows.Add(_Attendees, _Organization);
        SPListItem list = AttendeesDetailsList.Items.Add();
                   list["Title"] = properties.ListItemId;
                   list["ListOfAttendee"] = _Attendees;