我正在学习如何使用 Node.js。此时,我有一个如下所示的 XML 文件:
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>
我正在尝试在我的 Node 应用程序中加载此 XML。加载后,我只想得到 url
包括使用 <article:
的元素元素。在这个时候,我被困住了。现在,我正在使用 XML2JS通过以下方式:
var parser = new xml2js.Parser();
fs.readFile(__dirname + '/../public/sitemap.xml', function(err, data) {
if (!err) {
console.log(JSON.stringify(data));
}
});
当console.log
语句执行后,我只是在控制台窗口中看到一堆数字。像这样的:
{"type":"Buffer","data":[60,63,120, ...]}
我错过了什么?
最佳答案
使用 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);
});
关于javascript - 在 Node.js 中读取 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32873100/