Sunday, September 9, 2018

nlapiStringToXML not escaping special characters

Using nlapiStringToXML API and the value of the string data contains "<" or "&" throws an Unexpected Error.

This article shows how to automatically escape these characters and avoid the error.

 

Sample script:

1. Deploy the script below as a suitelet

function getXMLString(request,response){
var dom = '& some values here <';
nlapiLogExecution('DEBUG','dom',dom);
var CDOM = nlapiStringToXML('<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><EqtResp><val>'+ dom +'</val></EqtResp>');
var node = nlapiSelectNode(CDOM, "//*[name()='EqtResp']");
nlapiLogExecution('DEBUG', 'test', 'select value='+ nlapiSelectValue(node, "//*[name()='val']"));
}


2. Run the suitelet
3. Unexpected Error occurs such as:

org.xml.sax.SAXParseException: The reference to entity "anytextmessagehere" must end with the ';' delimiter.
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)

 

 

The special characters "<" and "&" are reserved characters in XML and if they are to be parsed as text they

have to be wrapped in a CDATA section. i.e.

 

var dom = "<![CDATA[&anytextmessagehere]]>"

function getXMLString(request,response){

var dom = '& some values here <';

var domparsed = "<![CDATA[" + dom + "]]>";

nlapiLogExecution('DEBUG','dom',domparsed);

var CDOM = nlapiStringToXML('<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><EqtResp><val>'+ domparsed +'</val></EqtResp>');

var node = nlapiSelectNode(CDOM, "//*[name()='EqtResp']");

nlapiLogExecution('DEBUG', 'test', 'select value='+ nlapiSelectValue(node, "//*[name()='val']"));

}

Note:

  • Characters like "<" and "&" are illegal in XML elements
  • - "<" will generate an error because the parser interprets it as the start of a new element.
  • "&" will generate an error because the parser interprets it as the start of an character entity.
  • Everything inside a CDATA section is ignored by the parser. A CDATA section starts with "<![CDATA[" and ends with "]]>"

 

 

 

 

No comments:

Post a Comment