On this page:

21.15XML API

 

The Smile CDR Javascript Execution Environment has basic facilities for working with XML documents.

21.15.1XPath Expressions

 

Many of the JavaScript operations for working with XML use XPath expressions. XPath is a powerful tool, but it can be tricky to get right. There is an online tool found at http://xpather.com/ that can be helpful in building and testing expressions.

XML Namespaces and XPath

Consider the following document:

<animals:Dog xmlns:animals="http://animals">
    <animals:Legs>4</animals:Legs>
</animals:Dog>

This document uses an XML Namespace and prefix to declare the element names Dog and Legs. Extracting values from these elements can be done with two different XPath forms:

  • Wildcard prefix: /*:Dog/*:Legs/text()
  • Specific prefix: /animals:Dog/animals:Legs/text()

21.15.2Function: getXPathValue(xpath)

 

This function returns a String containing the output of an XPath expression executed against the document (or an element within the document).

For example, given the document:

<Books>
    <Book id='123'/>
</Books>

The following script will output the text "123".

let id = document.getXPathValue('/Books/Book/@id');
Log.info('The ID is: ' + id);

21.15.3Function: getXPathValues(xpath)

 

This function returns an Array of Strings containing the output of an XPath expression executed against the document (or an element within the document).

For example, given the document:

<Books>
    <Book id='123'/>
    <Book id='456'/>
</Books>

The following script will output the text "123".

let ids = document.getXPathValue('/Books/Book/@id');
Log.info('The IDs are: ' + ids);

21.15.4Function: getXPathElements(xpath)

 

This function returns an array of XML child elements resulting from the evaluation of an XPath expression executed against the document (or an element within the document). Entries in the array will be XML elements and can have further XML functions applied to them.

For example, given the document:

<Books>
    <Book><title>Why Dogs are Better</title></Book>
    <Book><title>Why Cats are Better</title></Book>
</Books>

The following script will place the book titles into an array.

let titles = []; // create an empty array
let books = theDocument.getXPathElements('/Books/Book');
for (let index = 0; index < books.length; index++) {
  let book = books[index];
  let title = book.getXPathValue('title');
  titles.push(title);
}