Programmatically generate/update data for an InfoPath Form and save it in a SharePoint Form Library

Steps
 1) Create an Infopath form using the Microsoft InfoPath desinger. and publish the infoPath form into respective form library. I also created an empty form in the form library based on this template (BLANK.xml). This example opens an empty form (BLANK.xml) from the form library, reads it into an xml document, parses the xml document to update the fields, and then saves the xml document as a new file back to the form library.

2)
// opens the site
SPWeb webSite = new SPSite(txtUrl.Text).OpenWeb();
// gets the blank file to copySPFile BLANK = webSite.Folders["Test1"].Files["BLANK.xml"];
// reads the blank file into an xml documentMemoryStream inStream = new MemoryStream(BLANK.OpenBinary());
XmlTextReader reader = new XmlTextReader(inStream);
XmlDocument xd = new XmlDocument();
xd.Load(reader);
reader.Close();
inStream.Close();
//gets the root element from the xml documentXmlElement root = xd.DocumentElement;
//the loop counter is started at 2 to skip past the namespace tags and start at the data fieldsfor(int index=2; index<root.ChildNodes.Count; index++)
{
//insert code to parse the xml to update the fields}

// saves the XML Document back as a fileSystem.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
SPFile newFile = webSite.Folders["Test1"].Files.Add("Test_Document.xml", (encoding.GetBytes(xd.OuterXml)), true);


XPath queries could also be used to find and update fields in the xml instead of or in addition to looping through the nodes of the xml document. Another alternative to this would be to use the myschema.xsd from the .xsn file and load a strongly typed dataset based on that schema with the xml, update the fields in the dataset, then write the dataset to xml and appending the proper header tags at the top xml to include the InfoPath namespace information. This could also be slightly modified to open an existing form in a SharePoint form library, update the data elements, and save it back to the form library.

Comments

Popular posts from this blog

SharePoint 2016 and 2019 Ports

Clear fields based on drop-down values in PowerApps

Hide a SharePoint list field based on user group using JQuery Webservice in 2010