如何在JavaScript node.js中将xml文件解析为数组 [英] How to parse xml file to array in JavaScript node.js
本文介绍了如何在JavaScript node.js中将xml文件解析为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是初学者,我在解析数据时从xml文件到Node.js中的数组有问题吗?
I'm beginner and I have problem with parse data from xml file to array in Node.js?
来自xml的数据:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<record>
<Name>Apple</Name>
<Code>AP</Code>
<Price>2,5</Price>
</record>
<record>
<Name>Kiwi</Name>
<Code>KI</Code>
<Price>1,5</Price>
</record>
</xml>
我希望这样的数组:
var array = [
{ Name: 'Apple', Code: 'AP', Price: '2,5'},
{ Name: 'Kiwi', Code: 'KI', Price: '1,5'}
];
@EDIT - 我们更接近
@EDIT - we're closer
我试图使用xml2js npm,结果是:
I was trying to use xml2js npm, result was:
{
"xml": {
"$": {
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance
},
"record": [
{
"Name": [
"Apple"
],
"Code": [
"AP"
],
"Price": [
"2,5"
]
},
{
"Name": [
"Kiwi"
],
"Code": [
"KI"
],
"Price": [
"1,5"
]
}
]
}
}
我目前的代码:
var fs = require('fs');
var parseString = require('xml2js').parseString;
fs.readFile('test_data.xml', function(err, data){
parseString(data, function (err, result)
{
console.log(JSON.stringify(result, null, 2));
});
});
推荐答案
在npm上查看众多XML解析器包中的一个。
Check out one of the many XML Parser Packages on npm.
例如: xml2js
var parseString = require('xml2js').parseString;
var xml = "<root>Hello xml2js!</root>"
parseString(xml, function (err, result) {
console.dir(result);
});
如果您在阅读xml文件时需要帮助,请查看nodeJs文件系统库。
If you need help reading the xml File in, check out the nodeJs File System Libary.
var fs = require('fs');
fs.readFile('/etc/data.xml', (err, data) => {
if (err) throw err;
console.log(data);
});
编辑:
在一个函数中完成所有操作:
To make it all in one function:
function loadXML(cb) {
fs.readFile('test_data.xml', function(err, data){
parseString(data, function (err, result) {
cb(result.xml.record)
});
});
}
loadXML(function(yourRecods) {
// do whatever
});
这篇关于如何在JavaScript node.js中将xml文件解析为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文