nodejs解析xml文件方式(xml->json)
更新時間:2024年08月29日 08:47:12 作者:slient_love
這篇文章主要介紹了nodejs解析xml文件方式(xml->json),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
nodejs解析xml文件(xml->json)
nodejs解析xml文件的方式有很多
- xml2j
- xmlreader
- xmldom+xpath
- xmldoc
- xml-js
- …
可自行訪問官網(wǎng),里面有用法示例,在此不再進行贅述。
在開發(fā)中要解析的xml文件內(nèi)容
如下:
<xml xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882' xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882' xmlns:rs='urn:schemas-microsoft-com:rowset' xmlns:z='#RowsetSchema'> <s:Schema id='RowsetSchema'> <s:ElementType name='row'> <s:AttributeType name='grade' rs:number='1'> <s:datatype dt:type='varchar' dt:maxLength='64'/> </s:AttributeType> <s:AttributeType name='sex' rs:number='8'> <s:datatype dt:type='numeric' dt:maxLength='22'/> </s:AttributeType> </s:ElementType> </s:Schema> <rs:data> <z:row grade='2' sex='男' /> </rs:data> </xml>
業(yè)務上需要獲取z:row 里面的屬性,即grade='2' sex='男',搞了一下午,使用xml2j,xmlreader…獲取到的數(shù)據(jù)都不是想要的結果,最后使用xml-js一下就成功了。
開心撒花~
代碼如下:
let filepath = 'H:\\workcode\\xml\\TCOMPANY.xml'
const fs = require('fs');
let convert = require('xml-js');
let xml = fs.readFileSync(filepath,'utf-8');
let result1 = convert.xml2json(xml, {compact: true, spaces: 4});
console.log(result1);結果如下:
{
"xml": {
"_attributes": {
"xmlns:s": "uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882",
"xmlns:dt": "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882",
"xmlns:rs": "urn:schemas-microsoft-com:rowset",
"xmlns:z": "#RowsetSchema"
},
"s:Schema": {
"_attributes": {
"id": "RowsetSchema"
},
"s:ElementType": {
"_attributes": {
"name": "row"
},
"s:AttributeType": [
{
"_attributes": {
"name": "grade",
"rs:number": "1"
},
"s:datatype": {
"_attributes": {
"dt:type": "varchar",
"dt:maxLength": "64"
}
}
},
{
"_attributes": {
"name": "sex",
"rs:number": "8"
},
"s:datatype": {
"_attributes": {
"dt:type": "numeric",
"dt:maxLength": "22"
}
}
}
]
}
},
"rs:data": {
"z:row": {
"_attributes": {
"grade": "2",
"sex": "男"
}
}
}
}
}成功啦!
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Node.js+Socket.io實現(xiàn)雙人在線五子棋對戰(zhàn)
這篇文章主要為大家詳細介紹了Node.js+Socket.io實現(xiàn)雙人在線五子棋對戰(zhàn),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-05-05
詳解node+express+ejs+bootstrap構建項目
本篇文章主要介紹了詳解node+express+ejs+bootstrap構建項目,非常具有實用價值,需要的朋友可以參考下2017-09-09

