使用Node.JS xml2js将XML转换为JSON时处理XML属性

问题描述 投票:0回答:2

我正在尝试使用Node.JS上的xml2js将XML文件转换为JSON。

当我点击一个属性时,它将替换为'_'和'$'字符。

我完全知道JSON没有XML所具有的属性的概念。

如何转换以下XML文档:

<id>
  <name language="en">Bob</name>
  <name>Alice</name>
</id>

转换为JSON格式,例如:

{
    "id": {
        "name": [{
            "language": "en",
            "text": "bob"
        }, "alice"]
    }
}

我在Node.JS中的代码是:

const fs = require('fs');
const util = require('util');
const json = require('json');
const xml2js = require('xml2js');

const xml = fs.readFileSync('./test.xml', 'utf-8', (err, data) => {
  if (err) throw err;  
});

const jsonStr = xml2js.parseString(xml, function (err, result) {
  if (err) throw err;
    console.log(util.inspect(JSON.parse(JSON.stringify(result)), { depth: null }));
});

当前输出为:

{ id: { name: [ { _: 'Bob', '$': { language: 'en' } }, 'Alice' ] } }
node.js json xml xml2js
2个回答
1
投票

将输出

{
  id: { name: [ { language: 'en', text: 'Bob' }, { text: 'Alice' } ] }
}

代码:

const fs = require('fs');
const util = require('util');
const json = require('json');
const xml2js = require('xml2js');

const xml = fs.readFileSync('./test.xml', 'utf-8', (err, data) => {
  if (err) throw err;  
});

const jsonStr = xml2js.parseString(xml, function (err, result) {

  const nameArray = result.id.name;

  const newNameArray = nameArray.map(nameValue => {
    let text = '';
    let attributes = {};
    if (typeof nameValue === 'string') {
      text = nameValue
    } else if (typeof nameValue === 'object') {
      text = nameValue['_']
      attributes = nameValue['$']
    }
    return {
      ...attributes,
      text
    }
  })

  const newResult = {
    id: {
      name: newNameArray
    }
  }

  if (err) throw err;
    console.log(util.inspect(JSON.parse(JSON.stringify(newResult)), { depth: null }));
});

1
投票

这样的东西

const xml = `
<id>
  <name language="en">Bob</name>
  <name>Alice</name>
</id>`

const { transform } = require('camaro')

const template = {
    id: {
        name: ['id/name', {
            lang: '@language',
            text: '.'
        }]
    }
}

;(async function () {
    console.log(JSON.stringify(await transform(xml, template), null, 4))
})()

输出

{
    "id": {
        "name": [
            {
                "lang": "en",  
                "text": "Bob"  
            },
            {
                "lang": "",    
                "text": "Alice"
            }
        ]
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.