XML 指可扩展标记语言(EXtensible Markup Language)
npm里有包xml2js可以处理xml。
引入xml2js
1 | const xml2js = require('xml2js') |
生成xml内容
xml2js有Builder对象
1 | const builder = new xml2js.Builder({ |
假设我们有如下数据:1
2
3
4
5
6
7
8
9
10
11
12
13
14let obj = {
"_id": "5816b415b06d1d32157790b1",
"title": "圣墟",
"author": "辰东",
"longIntro": "在破败中崛起,在寂灭中复苏。沧海成尘,雷电枯竭,那一缕幽雾又一次临近大地,世间的枷锁被打开了,一个全新的世界就此揭开神秘的一角……",
"cover": "/agent/http%3A%2F%2Fimg.1391.com%2Fapi%2Fv1%2Fbookcenter%2Fcover%2F1%2F1228859%2F1228859_d14f18e849b34420904ead54936e440a.jpg%2F",
"majorCate": "玄幻",
"minorCate": "东方玄幻",
"lastChapter": "正文卷 第1357章 原来是它!",
"rating": {
"count": 56765,
"score": 8.75,
},
}
当我们调用builder.buildObject(obj)方法后,1
let xml = builder.buildObject(obj)
输出结果如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14<xml>
<_id>5816b415b06d1d32157790b1</_id>
<title>圣墟</title>
<author>辰东</author>
<longIntro>在破败中崛起,在寂灭中复苏。沧海成尘,雷电枯竭,那一缕幽雾又一次临近大地,世间的枷锁被打开了,一个全新的世界就此揭开神秘的一角……</longIntro>
<cover>/agent/http%3A%2F%2Fimg.1391.com%2Fapi%2Fv1%2Fbookcenter%2Fcover%2F1%2F1228859%2F1228859_d14f18e849b34420904ead54936e440a.jpg%2F</cover>
<majorCate>玄幻</majorCate>
<minorCate>东方玄幻</minorCate>
<lastChapter>正文卷 第1357章 原来是它!</lastChapter>
<rating>
<count>56765</count>
<score>8.75</score>
</rating>
</xml>
解析xml内容
xml有Parser对象1
2
3const parser = new xml2js.Parser({
explicitArray: false,
})
现在对上面的xml进行解析:1
2
3
4parser.parseString(xml, (err, content) => {
if (err) console.error(err)
console.log(content)
})
输出结果:1
2
3
4
5
6
7
8
9
10
11
12{ xml:
{ _id: '5816b415b06d1d32157790b1',
title: '圣墟',
author: '辰东',
longIntro: '在破败中崛起,在寂灭中复苏。沧海成尘,雷电枯竭,那一缕幽雾又一次临近大地,世间的枷锁被打开了,一个全新的世界就此揭开神秘的一角……',
cover: '/agent/http%3A%2F%2Fimg.1391.com%2Fapi%2Fv1%2Fbookcenter%2Fcover%2F1%2F1228859%2F1228859_d14f18e849b34420904ead54936e440a.jpg%2F',
majorCate: '玄幻',
minorCate: '东方玄幻',
lastChapter: '正文卷 第1357章 原来是它!',
rating: { count: '56765', score: '8.75' }
}
}
返回的是一个string,别忘了JSON.parse(content)获得对象。
其他
xml2js支持很多参数,具体参考官方文档。