Undefined result when parse xml to json with xml2js node js

2.1k views Asked by At

i got a problem when parsing an XML to JSON by using xml2js. Here's my xml.

<Tables>
<Table>
    <Id>TABLE1</Id>
    <Description>Test 1</Description>
    <FullName>TEST.CHEM.Customer</FullName>
    <Columns>
    <Column>
        <Id>1</Id>
        <Name>CustomerId</Name>
        <DataType>Number</DataType>
    </Column>
    <Column>
        <Id>2</Id>
        <Name>CustomerName</Name>
        <DataType>String</DataType>
    </Column>
    <Column>
        <Id>2</Id>
        <Name>ValidFrom</Name>
        <DataType>Date</DataType>
    </Column>
    </Columns>
</Table></Tables>

And here's my main. I follow snippet from that library for the figuredOutXML (input: xmlfile.parseString, output: data)

apiRoutes.get('/test', function(req, res) {
res.set('Content-Type', 'application/json');

figuredOutXML(function(err,data,data2){
    if(err){
        console.log("Error!");
        console.error(err.message);
    }else{
        var tableId = util.inspect(data2.Tables.Table.Id, false, null);
        res.status(200).send(JSON.stringify({
        INFO: 'SUCCESS',
        TABLE: tableId}));
    }

});

But i got undefined result for tableId. Is it something wrong with xml or the function?

2

There are 2 answers

0
dityagow On BEST ANSWER

This was carelessness, it will always undefined result because var tableId is string formatted not on JSON format see here, so when xml already parsed by xml2js parser it already json formatted. You can access it by result.Databases.Tables[0].Table[0].FullName based on above xml file.

2
Anh Thang Bui On

You can try with another package camaro with simply and easily change the desired result.

Example:

const xml = '<Tables>
<Table>
    <Id>TABLE1</Id>
    <Description>Test 1</Description>
    <FullName>TEST.CHEM.Customer</FullName>
    <Columns>
    <Column>
        <Id>1</Id>
        <Name>CustomerId</Name>
        <DataType>Number</DataType>
    </Column>
    <Column>
        <Id>2</Id>
        <Name>CustomerName</Name>
        <DataType>String</DataType>
    </Column>
    <Column>
        <Id>2</Id>
        <Name>ValidFrom</Name>
        <DataType>Date</DataType>
    </Column>
    </Columns>
</Table></Tables>'

const temp = {
    table_id: 'Tables/Table/Id'
    columns: ['/Tables/Table/Columns/Column', {
        column_id: 'Id',
        name: 'Name'
    }]
}

const transform = require('camaro')
const results = transform(xml, temp)

console.log(JSON.stringify(results, null, 2))

Results

{
    "columns": [
        {
        "column_id": "1",
        "name": "CustomerId"
        },
        {
        "column_id": "2",
        "name": "CustomerName"
        },
        {
        "column_id": "2",
        "name": "ValidFrom"
        }
    ],
    "table_id": "TABLE1"
}