简体   繁体   中英

xml2js parsing - how to extract metadata attribute value?

I am trying to create a custom json by extracting data with xml2parsing. So far I have this:

function createCustomJson(d{ 

    let dataFromXml = ""; 
    parseString(d, {trim: true}, function (err, result) {
        dataFromXml = JSON.stringify(result);
    });
    let dataJson = { data: [] };
    let dataObj = JSON.parse(dataFromXml);
    let dataForJson = dataObj.dataset.data[0];
    let metadataForJson = dataObj.dataset.metadata[0];         

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

    let json = JSON.stringify(dataJson);
} 

xml:

<?xml version="1.0" encoding="utf-8"?>
<dataset  xmlns="http://example.com"  xmlns:xs="http://www.w3.org/2001/XMLSchema-instance">
    <metadata>
          <item name="DATA_1" type="xs:string" length="2102"/>
          <item name="DATA_2" type="xs:string" length="24"/>
    </metadata>
    <data>
        <row>
            <value>active</value>
            <value>whatever</value>
        </row>
    </data>
</dataset>

I was able to extract all the values from "data", but don't know how to get the metadata item name (DATA_1 and DATA_2).

In console.log, for

metadataForJson.item[0]

I get

{ '$': { name: 'DATA_1', type: 'xs:string', length:'2102'} }

Don't know how to get value of '$' out, it always gives me sintax error. Any ideas? Thanx!

just try

metadataForJson.item[0].$.name

OR

metadataForJson.item[0]['$'].name

This related post may help https://stackoverflow.com/a/22028956/730733

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM