The CreatorCon Call for Content is officially open! Get started here.

How I can print element in a xml String

Suyash Joshi
Tera Contributor

Hello Everyone,

I am stuck in a problem in which I want to print only a single element in code.

The code as follow:-

var xmlString = "<test>" +
" <one>" +
" <two att=\"xxx\">abcd1234</two>" +
" <three boo=\"yah\" att=\"yyy\">1234abcd</three>" +
" <two>another</two>" +
" </one>" +
" <number>1234</number>" +
"</test>";

 

Any help will be greatful

Regards,

Suyash

1 ACCEPTED SOLUTION

You're going to need to use XMLDocument2 | ServiceNow Developers

 

Something like 

 

/*
 * Retrieves the attribute value from the given XML.
 * Params:
 *  xmlDoc - XMLDocument2, XML document to parse
 * Returns:
 *  String, attribute value or null if not found
 */
function getAttributeKey (xmlDoc) {
  var node = xmlDoc.getNode("/test/one/two");
  if (node != null) {
    return node.getAttribute("att");
  } else {
    return null;
  }
}

// Example usage:

var xmlString = "<test>" +
                "  <one>" +
                "    <two att=\"xxx\">abcd1234</two>" +
                "    <three boo=\"yah\" att=\"yyy\">1234abcd</three>" +
                "    <two>another</two>" +
                "  </one>" +
                "  <number>1234</number>" +
                "</test>";

var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(xmlString);

var attribute = getAttributeKey(xmlDoc);
if (attribute != null) {
  gs.info("The attribute value is: " + attribute);
} else {
  gs.info("The attribute value is not found.");
}

 


Help others to find a correct solution by marking the appropriate response as accepted solution and helpful.

View solution in original post

5 REPLIES 5

I want to print only element now (abcd1234, 1234abcd, another, 1234 ), My first requirement has fulfilled.