Wednesday, June 4, 2014

How to convert XML String to XML Element in IBM BPM

Below post illustrates on how typecast an XML string to XML Element in IBM BPM.

I have recently encountered an issue of this sort in one of my projects.
Traditionally, below code snippet will work in converting an XML string to XML Element.

tw.local.xmlEleVar=Packages.com.lombardisoftware.core.XMLUtilities.stringToElement(tw.local.xmlString)

Where tw.local.xmlEleVar is of type tw.object.XMLElement and tw.local.xmlString.

But in later version of IBM BPM v8.0 (Starting from V8.0.1), the package used above seems to be deprecated. When the above snippet is used in ibm bpm v8.01 it started giving error. Then after some trail and error we found that the expression below, itself type casts the xmlstring to XMLElement.
tw.local.xmlEleVar = tw.local.xmlString



Above expression will work if there are no special characters in that xmlString i.e the xmlString should contain xml like <sampleElement/> but not like this &lt;sampleElement/&gt;. 

But most of the time when we had to change the xmlstring to xmlelement we get an xml like this &lt;sampleElement/&gt (for example when get the xmlstring from the response of a web service call or rest service call). In this scenario, we can just convert all the html escape characters to the corresponding special charater (&lt; to < and &gt; to > etc.) and use the above expression to convert the xmlstring to xmlelement. Below js method will you convert all the escape characters that are normally found back to special characters.

function getXml(getStr) {

var regExLi = /<\/li>/gi; //RegEx to find </li>

var regExHTML = /<\S[^>]*>/g; //RegEx to find HTML Tags
var regExAnd = /&amp;/g; //to find ampersand as HTML entity
var regExSpace = /&nbsp;/g; //to find whitespace as HTML entity
var regExlt = /&lt;/g; //to find < as HTML entity
var regExgt = /&gt;/g; //to find > as HTML entity
getStr = getStr .replace(regExLi, "\n"); //replace </li> with \n
getStr = getStr .replace(regExAnd, "&"); //replace &amp; with &
getStr = getStr .replace(regExSpace, " "); //replace &nbsp; with simple whitespace
getStr = getStr .replace(regExlt, "<"); //replace &lt; with <
getStr = getStr .replace(regExgt, ">"); //replace &gt; with >

return getStr;
}

If you find any more special characters in you xmlstring you can always enhance the above method to suit your needs.
Hope this is help full.



5 comments:

  1. What is the getTxt function code?

    ReplyDelete
  2. I see it's getStr instead of getTxt

    ReplyDelete
  3. Oh Yeah ..it is a typo.. Thanks for pointing Rob. I have rectified it.

    ReplyDelete
  4. Could anyone help me with a method to convert the xml string to xml document.

    ReplyDelete
  5. Could anyone help me with a method to convert the xml string to xml document.

    ReplyDelete