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?
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.
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.
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); });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With