Yevgeny Simkin
Yevgeny Simkin

Reputation: 28389

What's the simplest way to parse an XML string in Node.js?

I'm looking around and not seeing an obvious way to parse XML in Node. I'm assuming that there's some relatively straight forward XML object that I can pass a String or url to, but I'm not finding anything like that in the spec. Do I need an external lib? and if so, which one would you guys recommend? I don't need xPath (though I wouldn't mind it) as long as I can walk the tree in an obvious way (test if nodeType == ElementNode and loop through children).

Upvotes: 6

Views: 42779

Answers (4)

Ilyas Assainov
Ilyas Assainov

Reputation: 2069

If you're using Express along with body parser, the simplest way would be to use express-xml-bodyparser. It allows to parse XML for all routes or specific ones, depending on your scenario

All routes:

const xmlparser = require('express-xml-bodyparser');
// .. other middleware ... 
app.use(express.json());
app.use(express.urlencoded());
app.use(xmlparser());
// ... other middleware ... 

app.post('/receive-xml', function(req, res, next) {

  // req.body contains parsed XML as JSON

});

Specific routes:

app.post('/receive-xml', xmlparser({trim: false, explicitArray: false}), function(req, res, next) {
  // req.body contains parsed XML as JSON  
});

Upvotes: 1

user568109
user568109

Reputation: 48003

I suggest xml2js, a simple XML to JavaScript object converter. You can then iterate the resulting object. Code snippet from the page :

var parseString = require('xml2js').parseString;
var xml = "<root>Hello xml2js!</root>"
parseString(xml, function (err, result) {
    console.dir(result);
});

You can install it by using npm install xml2js

Upvotes: 14

istos
istos

Reputation: 2662

If it isn't an absolute requirement that it has to be done server side, then on the client you could use XMLSerializer to parse into string, and DOMParser to parse into DOM.

XMLSerializer Example (from DOM to string):

var XMLS = new XMLSerializer();
var elem = document;
var xml_str = XMLS.serializeToString(elem);
console.log(xml_str);

DOMParser Example (from string to DOM):

var parser = new DOMParser();
var doc = parser.parseFromString(xml_str, "application/xml");
console.log(doc);

Upvotes: -4

Jorge Israel Pe&#241;a
Jorge Israel Pe&#241;a

Reputation: 38626

There are a variety of XML modules listed here where perhaps you may find one that works best for you. A popular one that I'm aware of is sax-js. There are also libxml bindings if you're already familiar with that library.

Upvotes: 3

Related Questions