写了一个ES6(ES2015)模块可用的xml2json插件,给大家分享一下

虽然xml2json有CMD版本的,但是我发现在写React的时候发觉怎么都不能用require导进去(可能是我哪里配置问题,但是太麻烦了),所以干脆自己写了一个xml2json的插件

xml2json主要用处就是将xml文件内容转换为json格式,如果需要还可以从json格式转为xml格式

废话不多说,先上个github链接,希望能帮到你 :P

https://github.com/LaiHuanMin/xml2json-es2015

下面是readme文档

XML2JSON

XML2JSON for ES2015 Module (Not CommonJS Module)

Install

Not Upload to NPM right now, you can get xml2json by git clone

Usage

import xml2json from './kit/xml2json'; //Not push xml2json to NPM now,so you can use relative or absolute path

//parse your xml string here
function parseToJSON(xml){
    return xml2json.toJSON(xmlContent);
} 

//parse your json to XML Object here
function parseToXML(json){
    return xml2json.toXML(test2);
}

//parse your xml string to really XML Object
function getOriginXML(xmlString){
    return xml2json.getXmlObject(xmlContent)
}

//simulate ajax XML file and parse data
function ajaxData(){
    axios.get('./my.xml').then(success=>{
        //parse data
        var xmlContent = success.data
        var xmlObject = getOriginXML(xmlContent);
        var json = parseToJSON(xmlContent);
        var parsedXML = parseToXML(json);
    }).catch(error=>{
        //handle error
    })    
}

JSON Format

if you invoke xml2json.toJSON(xmlstring), the return JSON Format Will be like this

    {
        tagName: "Root TagName",
        hasAttr: true | false, //indicate whether there's attributes in current tag
        isParent: true | false, //indicate whether there's child tags in current tag        
        content: "this is content", //show current tag's content, it's contains arrow tag if it's not leaf node (just child node,without own children) 
        attr: { //show current tag's attributes set, it's just like <Example attr1="attr1's val" attr2="attr2's val"></Example>, if there's no attr, the attr attrbutes will be a empty object;
            attr1: "attr1's val",
            attr2: "attr2's val"
        },
        children: [ //it's same struture.if some child without own children, it's will don't own children key, and the isParent will be set to false
            {
                ...
            }
        ]
    }

Infomation

The xml2json plugin is used in es2015 module, write with es2015 syntax, may not suit for CommonJS module.

If it can help to you, please give me a star, Thanks a lot! :P

License

MIT

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值