This article would share a code-snippet that updates the Infopath form XML. In my portal, I’m performing data-acquision using Infopath forms for a Infopath-content type workflow scenario. This scenario is all about an employee appraisal workflow. I’ve a business requirement to mark the ‘IsManager’ column as ‘Yes’ , when the employee gets promoted as Manager. This forced me to think a way to programmatically update the Infopath form XML using c# code. The following is the c# code that can be used to programmatically update the Infopath Form XML.
SPWeb oWeb = SPContext.Current.Web;
SPList _list = oWeb.Lists[“TestFormLib”];
MemoryStream oMemoryStream = new MemoryStream(item.File.OpenBinary());
XmlTextReader oReader = new XmlTextReader(oMemoryStream);
XmlDocument oDoc = new XmlDocument();
oDoc.Load(oReader);
oReader.Close();
oMemoryStream.Close();
XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(oDoc.NameTable);
nameSpaceManager.AddNamespace(“my”, “http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-06-11T12:44:57“);
doc.DocumentElement.SelectSingleNode(“my:IsManager”, nameSpaceManager).InnerText = “Yes”;
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
SPFile oSPFile = oWeb.Folders[“TestFormLib”].Files.Add(item.File.Name.ToString(), (encoding.GetBytes(doc.OuterXml)), true);
item.File.Update();
Pingback: Programmatically update Infopath Form XML using c# code - My experiments with SharePoint, Azure and .NET using Visual Studio
Sundar..Thanks for the info!!!
Is the above code for work flow or I can use it for simple SharePoint List
You inspired me so i bring you my solution
—–
//NOTE : You may also need to use web.allowUnsafeUpdate = true;
SPList myList = SPContext.Current.Web.Lists[“myList”];
SPListItem item = myList.GetItemById(123);
XmlDocument xmlItem = new XmlDocument();
//Open XML file and load it into XML document
using (Stream streamItem = item.File.OpenBinaryStream())
{
xmlItem.Load(streamItem);
}
XPathNavigator navItem = xmlItem.CreateNavigator();
//Redefine NameSpaceManager (Generate the NameSpace manager for this item)
navItem.MoveToFollowing(XPathNodeType.Element);
XmlNamespaceManager nsManager = new XmlNamespaceManager(new NameTable());
foreach (KeyValuePair ns in navItem.GetNamespacesInScope(XmlNamespaceScope.All))
{
if (ns.Key == String.Empty)
{
nsManager.AddNamespace(“def”, ns.Value);
}
else
{
nsManager.AddNamespace(ns.Key, ns.Value);
}
}
//Change your value here….
navItem.SelectSingleNode(“/my:myFields/my:yourFieldName”, nsManager);
//Save the modified xml into the item
byte[] xmlData = System.Text.Encoding.UTF8.GetBytes(navItem.OuterXml);
item.File.SaveBinary(xmlData);
item.File.Update();
Have a nice day!