【发布时间】:2015-12-28 15:40:18
【问题描述】:
我正在学习如何使用 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。加载时,我只想获取包含使用 <article: 元素的 url 元素。在这个时候,我被困住了。现在,我通过以下方式使用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, ...]}
我错过了什么?
【问题讨论】:
-
还有什么理由将其转换为 JSON?使用 XMLDOM,XPAth 用于节点,因为您知道它是 XML 并且可以使用 XPath 将是另一个需要考虑的途径。
标签: javascript xml node.js