【发布时间】:2016-08-14 07:08:28
【问题描述】:
我是初学者,在 Node.js 中将数据从 xml 文件解析到数组时遇到问题?
来自 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 - 我们更接近了
我尝试使用xml2js npm,结果是:
{
"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));
});
});
【问题讨论】:
标签: javascript arrays xml node.js