如何在Javascript中读取XML文件? [英] How to read XML file in Javascript?

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

问题描述

我正在为Discord创建一个机器人。我正在从互联网上下载星座XML文件。 XML文件结构如下:

I'm creating a bot for the Discord. I'm downloading a horoscope XML-file from the Internet. The XML-file structure is as follows:

<?xml version="1.0" encoding="utf-8"?>
<horo>
<date yesterday="04.01.2019" today="05.01.2019" tomorrow="06.01.2019"/>

<aries>
<yesterday>
Text 1
</yesterday>
<today>
Text 2
</today>
<tomorrow>
Text 3
</tomorrow>
</aries>

......

</horo>

我尝试用javascript阅读它:

I try to read it in javascript:

const fs = require('fs');
var HoroscopeData = new Object();

fs.readFile('./module/Horoscope.xml', 'utf8', function(err, data){

  if(err) {
    console.error("ERROR");
  }

  console.log("OK");
  HoroscopeData = data;
}

console.log(HoroscopeData);

在控制台中,我看到的是同样的东西XML文件

In the console, I see the same thing that is in the XML-file

但是我不明白如何引用 HoroscopeData字段。
如何返回 aries- > today?

But I don't understand how to refer to "HoroscopeData" fields. How do I return a string which is in "aries->today"?

推荐答案

您可以使用 https://www.npmjs.com/package/xml-js

要转换XML到JSON,您可以使用内置的javascript JSON函数 JSON.parse(target)或JSON.stringify(target)

To convert the XML to JSON where you can access it using the built in javascript JSON functions JSON.parse(target) or JSON.stringify(target)

引用此程序包,这是将XML转换为JSON的简单示例

quoting this package, here is an example of how simple it is to turn XML into JSON

var convert = require('xml-js');
var xml =
'<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' +
'    <title>Happy</title>' +
'    <todo>Work</todo>' +
'    <todo>Play</todo>' +
'</note>';
var result1 = convert.xml2json(xml, {compact: true, spaces: 4});
var result2 = convert.xml2json(xml, {compact: false, spaces: 4});
console.log(result1, '\n', result2);

如果您不喜欢直接使用XML进行操作,这可能会对您有所帮助,因为与JSON交互非常简单

If you are uncomfortable working directly in XML, this may help you because interacting with JSON is JavaScript is simple.

这是如何从JSON中提取您需要的内容,JSON-xml将您的XML转换为

This is how to then extract what you need from the JSON that xml-js converts your XML to

var convert = require('xml-js');
var xml =
'<?xml version="1.0" encoding="utf-8"?>'+
'<horo>'+
'<date yesterday="04.01.2019" today="05.01.2019" tomorrow="06.01.2019"/>'+
'<aries>'+
'<yesterday>'+
'Text 1'+
'</yesterday>'+
'<today>'+
'Text 2'+
'</today>'+
'<tomorrow>'+
'Text 3'+
'</tomorrow>'+
'</aries>'+
'</horo>';

const rawJSON = convert.xml2json(xml, {compact: true, spaces: 4});
const convertedJSON = JSON.parse(rawJSON);
console.log(convertedJSON.horo.aries.today._text);

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

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