nodejs解析xml文件(xml->json)

nodejs解析xml文件(xml->json)

nodejs解析xml文件的方式有很多:

  • xml2j
  • xmlreader
  • xmldom+xpath
  • xmldoc
  • xml-js

  • 点击可自行访问官网,里面有用法示例,在此不再进行赘述。今天在开发中要解析的xml文件内容如下:
<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>

业务上需要获取z:row 里面的属性,即grade='2' sex='男',搞了一下午,使用xml2j,xmlreader…获取到的数据都不是想要的结果,最后使用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": "男"
                }
            }
        }
    }
}

成功!

你可能感兴趣的:(软件开发)