TAGS :Viewed: 7 - Published at: a few seconds ago

[ accesing xml content from node.js ]

I have a bunch of XML documents in MarkLogic database. I am working on a node.js middletier, it needs to pass on certain properties of all xml documents in a certain collection into a JSON array.

So far I have this:

var marklogic = require('marklogic');
var my = require('./my-connection.js');

var db = marklogic.createDatabaseClient(my.connInfo);
var qb = marklogic.queryBuilder;

).result( function(documents) {
    console.log('The alerts collection:')
    documents.forEach( function(document) {
      //console.log('\nURI: ' + document.uri);
      var aObj = document.content
      //var alert = aObj.getElementsByTagNameNS("http://example.com/sccs/alert","alert");
      console.log('Alert: ' + document.content);
}, function(error) {
    console.log(JSON.stringify(error, null, 2));

Which gives me the content back.

Example result:

Alert: <?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0"?>
<obj:object xmlns:obj="http://marklogic.com/solutions/obi/object">
  <obi:metadata xmlns:obi="http://marklogic.com/solutions/obi" createdBy="admin" createdDateTime="2015-09-23T20:42:48.562829Z" lastUpdatedBy="admin" lastUpdatedDateTime="2015-09-23T20:42:48.562829Z"/>
    <alert xmlns="http://example.com/sccs/alert">
      <obj:property sourceCount="1">
      <obj:property sourceCount="1">
        <position>{"type":"Point", "coordinates":[52.2, 4.3]}</position>
      <obj:property sourceCount="1">
        <scc:id xmlns:scc="http://example.com/sccs">2a65b4cc-acee-4675-a8ba-d8c5dfaac9dd</scc:id>
    <obj:workspace id="Public"/>
  <obj:sourceIds count="1">
    <source:id xmlns:source="http://marklogic.com/solutions/obi/source">42aebdc7-41aa-4695-b514-2bb63f85d47c</source:id>


I want to access for example the 'obj:content' element in this content.

In the Query Console I can do this by :

var alerts = fn.collection("alert").toArray();
var aXML = alerts[2].getElementsByTagNameNS("http://example.com/sccs/alert","alert");

How can I do this from node.js?

(I do not understand the object type returned from the query in node.js)

Answer 1

The MarkLogic node.js API returns XML documents as strings; you'll need to use an XML parser in order to query, project, or process that XML. There are lots of modules for interacting with XML on npm, see

You may find it easier to use a server-side transformation with MarkLogic, and convert your XML documents to JSON first: http://docs.marklogic.com/guide/node-dev/extensions#id_78179