Sunday, March 2, 2014

C# Update InfoPath by passing in the XPath

C# code snippet to update the InfoPath XML file in a SharePoint library.

Sample parameters:
websiteUrl: http://sharepoint
library Name: InfoPath Library
list Id: 1
xpath: /my:myFields/my:Employees/my:Employee[my:ID='123']/my:Location
value: San Jose

What it does:
In the repeating group Employees, locate the employee whose ID is 123, and update the location to San Jose.



Hierarchy:
-->myFields
--->Employees
---->Employee
----->ID
----->Location


public string SetInfopathValue(string websiteUrl, string libraryName, int listId, string xpath, string value)
{
string output = "";
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(websiteUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists.TryGetList(libraryName);
SPListItem item = list.GetItemById(listId);
if (item != null)
{
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", oDoc.DocumentElement.NamespaceURI);

oDoc.DocumentElement.SelectSingleNode(xpath, nameSpaceManager).InnerText = value;

web.AllowUnsafeUpdates = true;

byte[] xmlData = System.Text.Encoding.UTF8.GetBytes(oDoc.OuterXml);
item.File.SaveBinary(xmlData);
item.File.Update();
output = "SUCCESS";
}
else
{
output = "file not found.";
}
}
}
});
}
catch (Exception e)
{
errorAlert("SetInfopathValue: " + e.ToString());
output += "SetInfopathValue : " + e.ToString();
}
return output;
}


Related Posts Plugin for WordPress, Blogger...