Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading XML file in Node.js

I'm learning how to use Node. At this time, I have an XML file that looks like this:

sitemap.xml

<?xml version="1.0" encoding="utf-8"?>  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">   <url>     <loc>http://www.example.com</loc>     <lastmod>2015-10-01</lastmod>     <changefreq>monthly</changefreq>   </url>    <url>     <loc>http://www.example.com/about</loc>     <lastmod>2015-10-01</lastmod>     <changefreq>never</changefreq>   </url>    <url>     <loc>http://www.example.com/articles/tips-and-tricks</loc>     <lastmod>2015-10-01</lastmod>     <changefreq>never</changefreq>     <article:title>Tips and Tricks</blog:title>     <article:description>Learn some of the tips-and-tricks of the trade</article:description>   </url> </urlset> 

I am trying to load this XML in my Node app. When loaded, I want to only get the url elements that include the use of the <article: elements. At this time, I'm stuck though. Right now, I'm using XML2JS via the following:

var parser = new xml2js.Parser(); fs.readFile(__dirname + '/../public/sitemap.xml', function(err, data) {     if (!err) {         console.log(JSON.stringify(data));     } }); 

When the console.log statement is executed, I just see a bunch of numbers in the console window. Something like this:

{"type":"Buffer","data":[60,63,120, ...]} 

What am I missing?

like image 795
user70192 Avatar asked Sep 30 '15 18:09

user70192


People also ask

How to read XML in Node JS?

Node. js has no inbuilt library to read XML. The popular module xml2js can be used to read XML. The installed module exposes the Parser object, which is then used to read XML.

How to parse XML response in NodeJS?

Open command prompt and type following command to generate a NodeJS, Express application. This command will generate an express application named nodejs-parse-xml. Type command cd nodejs-parse-xml. Type npm install to install the dependencies and modules.


2 Answers

use xml2json

https://www.npmjs.com/package/xml2json

fs = require('fs');  var parser = require('xml2json');    fs.readFile( './data.xml', function(err, data) {      var json = parser.toJson(data);      console.log("to json ->", json);   });
like image 117
Sajith Mantharath Avatar answered Sep 18 '22 19:09

Sajith Mantharath


From the documentation.

The callback is passed two arguments (err, data), where data is the contents of the file.

If no encoding is specified, then the raw buffer is returned.

If options is a string, then it specifies the encoding. Example:

fs.readFile('/etc/passwd', 'utf8', callback); 

You didn't specify an encoding, so you get the raw buffer.

like image 38
Quentin Avatar answered Sep 22 '22 19:09

Quentin