I recently need to take part of an XML document and convert that portion to a string. The problem is Service-now.com javascript libraries currently don’t have a way to let you select a node in your xml document and change that node and its children to a text representation of an xml document with that node being a parent.

I finally decided to have my javascript access Java libraries to use a series of Java commands to convert my child node into a string.

For example, in the following XML string I want to extract, as a string, the “vitamins” node:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<food>
  <name>Avocado Dip</name>
  <mfr>Sunnydale</mfr>
  <serving units="g">29</serving>
  <calories total="110" fat="100"/>
  <total-fat>11</total-fat>
  <saturated-fat>3</saturated-fat>
  <cholesterol>5</cholesterol>
  <sodium>210</sodium>
  <carb>2</carb>
  <fiber>0</fiber>
  <protein>1</protein>
  <vitamins>
    <a>0</a>
    <c>0</c>
  </vitamins>
  <minerals>
    <ca>0</ca>
    <fe>0</fe>
  </minerals>
</food>

Here is the function that I came up with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function convertXmlNodeToString(node){
//
// convert an xml node into a string
//
// PARMS
// node - a java xml node
//
// RETURNS
// String representation of the xml node
//
var sw = new Packages.java.io.StringWriter();
var transformer = Packages.javax.xml.transform.TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(Packages.javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
var domSource = new Packages.javax.xml.transform.dom.DOMSource(node);
var streamResult = new Packages.javax.xml.transform.stream.StreamResult(sw);
transformer.transform(domSource, streamResult);
return sw.toString();
}

Now I am able to use XPATH to browse to a child node in an XMLDocument object using getNode(xpath), and then convert that node to a string.

1
2
3
4
5
6
7
8
9
10
//xmlstring is the xml blob that I displayed above

//create an xml document
var xmldoc = new XMLDocument(xmlstring);

//Get the Vitamins node
var vitaminNode = xmldoc.getNode("//vitamins");

//Convert that node and it's children to a string that I can reuse elsewhere
var vitaminString = convertXmlNodeToString(vitaminString);