JS JSON格式转XML

应涵容
2023-12-01

json格式转xml

  • 需要使用xml2js进行转换

  • 安装
    npm install xml2js

  • 使用

示例1:

const xml2js = require("xml2js");
const builder = new xml2js.Builder();
const obj2 = {
  name: "Super",
  Surname: "Man",
  age: 23
};

const xml2 = builder.buildObject(obj2);
console.log("", xml2);

const fs = require("fs");
fs.writeFile("output.xml", xml2, (err1) => {
  if (err1) {
    throw err1;
  }
  console.log("成功写入文件");
});

输出output.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
  <name>Super</name>
  <Surname>Man</Surname>
  <age>23</age>
</root>

示例2:

  1. 创建json文件,temp.json
{
  "menu": {
    "button": [
      {
        "type": "click",
        "name": "今日歌曲",
        "key": "V1001_TODAY_MUSIC",
        "sub_button": []
      },
      {
        "type": "click",
        "name": "歌手简介",
        "key": "V1001_TODAY_SINGER",
        "sub_button": []
      },
      {
        "name": "菜单",
        "sub_button": [
          {
            "type": "view",
            "name": "搜索",
            "url": "http://www.soso.com/",
            "sub_button": []
          },
          {
            "type": "view",
            "name": "视频",
            "url": "http://v.qq.com/",
            "sub_button": []
          },
          {
            "type": "click",
            "name": "赞一下我们",
            "key": "V1001_GOOD",
            "sub_button": []
          }
        ]
      }
    ]
  }
}
  1. json文件转成xml
const xml2js = require("xml2js");
const builder = new xml2js.Builder(); // 默认XML标头输出<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
// const builder = new xml2js.Builder({xmldec:false}); // XML标头输出 <?xml version="1.0"?>
// const builder = new xml2js.Builder({headless:true}); //省略XML标头
const fs = require("fs");

fs.readFile('temp.json',function(err,data){
  if(err) console.log('err',err);
  const xml2 = builder.buildObject(JSON.parse(data.toString()));
  fs.writeFile("output.xml", xml2.toString(), (err1) => {
    if (err1) {
      throw err1;
    }
  });
})
  1. 输出结果output.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<menu>
  <button>
    <type>click</type>
    <name>今日歌曲</name>
    <key>V1001_TODAY_MUSIC</key>
  </button>
  <button>
    <type>click</type>
    <name>歌手简介</name>
    <key>V1001_TODAY_SINGER</key>
  </button>
  <button>
    <name>菜单</name>
    <sub_button>
      <type>view</type>
      <name>搜索</name>
      <url>http://www.soso.com/</url>
    </sub_button>
    <sub_button>
      <type>view</type>
      <name>视频</name>
      <url>http://v.qq.com/</url>
    </sub_button>
    <sub_button>
      <type>click</type>
      <name>赞一下我们</name>
      <key>V1001_GOOD</key>
    </sub_button>
  </button>
</menu>
 类似资料: