用xml2js解析xml属性

时间:2018-07-02 11:15:35

标签: javascript xml xml2js

我想解析以下XML

<?xml version="1.0" encoding="utf-8"?>
<response status="ok">
<items offset="180" totalitems="18" >
    <item icontype="F" iconid="29" title="1999 - Blur - 13" />
    <item icontype="F" iconid="29" title="1999 - Chris Cornell - Euphoria Morning" />
    <item icontype="F" iconid="29" title="1999 - Emperor - IX Equilibrium" />
    <item icontype="F" iconid="29" title="1999 - Feeder - Yesterday Went Too Soon" />
    <item icontype="F" iconid="29" title="1999 - Foo Fighters - There Is Nothing Left To Lose" />
    <item icontype="F" iconid="29" title="1999 - Goo Goo Dolls - Dizzy Up The Girl" />
    <item icontype="F" iconid="29" title="1999 - Kid Rock - Devil Without A Cause" />
    <item icontype="F" iconid="29" title="1999 - Limp Bizkit - Significant Other" />
    <item icontype="F" iconid="29" title="1999 - Marilyn Manson - The Last Tour On Earth" />
    <item icontype="F" iconid="29" title="1999 - Metallica - S&amp;M" />
    <item icontype="F" iconid="29" title="1999 - Ministry - Dark Side Of The Spoon" />
    <item icontype="F" iconid="29" title="1999 - Nine Inch Nails - The Fragile" />
    <item icontype="F" iconid="29" title="1999 - Paradise Lost - Host" />
    <item icontype="F" iconid="29" title="1999 - Primus - Antipop" />
    <item icontype="F" iconid="29" title="1999 - Rage Against The Machine - The Battle Of Los Angeles" />
    <item icontype="F" iconid="29" title="1999 - Red Hot Chili Peppers - Californication" />
    <item icontype="F" iconid="29" title="1999 - Slipknot - Slipknot" />
    <item icontype="F" iconid="29" title="1999 - Stone Temple Pilots - No. 4" />
</items>
</response>

我需要在“ for”循环中使用所有“图标类型”和“标题”。

所以我尝试过...

parser.parseString(xmlstring, {trim: true}, function (err, result) {
    dataFromXml = JSON.stringify(result);
    });
var dataJson = { data: [] };
var dataObj = JSON.parse(dataFromXml);
var dataForJson = dataObj.response.data[0];
var itemsForJson = dataObj.response.items[0];

var pom = {};
for (var i = 0; i < dataForJson.row.length; i++) {
    for (var j = 0; j < dataForJson.row[0].value.length; j++) {

        pom["METADATA-ATTR-NAME"] = dataForJson.row[i].value[j]; 
    }
    dataJson.data.push(pom); 
} 

var json = JSON.stringify(dataJson);

log(itemsForJson.item[0]['$'].title)

但给我一个错误:回调错误:SyntaxError:JSON输入意外结束

0 个答案:

没有答案