Tag Archives: XML

How to access and manuipulate ActivityInstanceDestination XML field in Workflow

To access datafields in K2 workflow is pretty straigh forward, but to access the XML fields require a bit more work to get to the text. In the following, the K2 API code is used to access the InfoPath XML data

1) Load the XML field using XmlDocument. If you have more then one XML field used, then loop through the XMLfield, use a IF statement to determine which XML field to load

XmlDocument document = new XmlDocument();
for (int i = 0; i < WLItem.ProcessInstance.XmlFields.Count; i++)
{
    if (WLItem.ProcessInstance.XmlFields[i].Name == “ABC”)
    {  xmlDoc.LoadXml(WLItem.ProcessInstance.XmlFields[i].Value.ToString());
   }
}

2) Once loaded, because K2 uses the namespace “my”. create a XmlNamespaceManager (as shown in the code below). Why the use of XMLNamespaceManager? From MSDN (MSDN URL) XmlNamespaceMaanager explanation:

Resolves, adds, and removes namespaces to a collection and provides scope management for these namespaces.

The namespace manager implements enumeration support in addition to adding and retrieving namespaces. You can loop through the information saved in the namespace manager by using the foreach construct.

Because the namespace manager provides a string comparison with the prefix and namespaces as objects, there is a performance improvement when using the namespace manager over the direct comparison of a string

System.Xml.XmlNamespaceManager xmlNSMgr = new System.Xml.XmlNamespaceManager(xmlDoc.NameTable);
xmlNSMgr.AddNamespace(“my”, xmlDoc.DocumentElement.GetNamespaceOfPrefix(“my”));

XmlNode RemarksNode = xmlDoc.DocumentElement.SelectNodes(<Insert the node structure here>, xmlNSMgr).Item(0);

node structure example: /my:myFields/my:Approver/my:Approver_Remarks

Full example: XmlNode RemarksNode = xmlDoc.DocumentElement.SelectNodes(“/my:myFields/my:Approver/my:Approver_Remarks”, xmlNSMgr).Item(0);

3) Once the node has been selected, you can manipulate the innerText. Example, I am updating the innertext of the node comments

Approver_Remarks.InnerText = tbRemarks.Text;

4) Now this is when some additional steps need to be done:

StringWriter _SW = new StringWriter(); // create a stringwriter
XmlTextWriter _XmlW = new XmlTextWriter(_SW); // create a new xml textwriter, writing to the stringwriter
xmlDoc.WriteTo(_XmlW); // write the xmlDoc to the xmltextwriter
string UpdatedXml = _SW.ToString(); // store the stringwriter value

//pass the XML value back to the XmlField

WLItem.ActivityInstanceDestination.XmlFields[“ApproverComment”].Value = UpdatedXml;

WLItem.Actions[“Approve”].Execute(); // Execute the action to update the field