在 Node.js 中读取 XML 文件 [英] Reading XML file in Node.js

查看:86
本文介绍了在 Node.js 中读取 XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何使用 Node.js.此时,我有一个如下所示的 XML 文件:

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>

我正在尝试在我的 Node 应用程序中加载此 XML.加载时,我只想获取包含使用 元素的 url 元素.在这个时候,我被卡住了.现在,我通过以下方式使用 XML2JS:

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));
    }
});

console.log 语句被执行时,我只是在控制台窗口看到一堆数字.像这样:

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, ...]}

我错过了什么?

推荐答案

使用 xml2json

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);
 });

这篇关于在 Node.js 中读取 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆