三种XML字符串转js对象方法

前言

后端传来一个xml字符串数组 类似 ['<a>1</a>','<b>2</b>']
将它转为js对象方便后续操作
一、使用match正则匹配 简单易用
function transformXml(xmls){
	const data = {}
	// 匹配标签的正则表达式
	const tagRegExp = /(?<=(<)).*?(?=(>))/
	// 匹配数据的正则表达式
	const dataRegExp = /(?<=(>)).*?(?=(<))/
	let tagName = ''
	let tagData = ''
	for (let i = 0; i < xmls.length; i++) {
	    tagName = xmls[i].match(tagRegExp)[0]
	    tagData = xmls[i].match(dataRegExp)[0]
	    data[tagName] = tagData
	}
	return data
}
二、 通过操作dom来取值
//XMLs 是xml字符串数组 ['<xml>1</xml>','<xml>2</xml>']
function transformXML(XMLs){
    const data={}
    let str = ''
    //创建一个根节点
    const root = document.createElement("data")
    //拼接 xml字符串
    for (let i = 0; i < XMLs.length; i++) {
        str += XMLs[i]
    }
    //添加节点为根节点的子节点
    root.innerHTML = str
    //获取根节点所有子节点
    const children = root.childNodes
    // 遍历子节点获取标签名以及标签内容
    for (let i = 0;i<children.length;i++){
        data[children[i].nodeName] = children[i].innerHTML
    }
    return data
}

2022/3/8 更新

发现后端可能会传过来一个xml字符串 类似
const xml = `
        <a>
            <b bbb="这是b标签属性">123</b>
            <c ccc="这是c标签属性" ddd="这是c标签第二个属性">
                <d abc="这是属性">123</d>
                <e>123</e>
            </c>
        </a>
    `
这种情况下 之前的两种方法都不再能使用
三、递归调用将xml字符串转为js对象
	const xml = `
        <a>
            <b bbb="这是b标签属性">123</b>
            <c ccc="这是c标签属性" ddd="这是c标签第二个属性">
                <d abc="这是属性">123</d>
                <e>123</e>
            </c>
        </a>
    `

    function transformXml(xmls){
    	//创建xml对象
    	//IE如何创建xml对象不再介绍 自行百度 此创建方式仅对非IE浏览器有效
        let root = new DOMParser().parseFromString(xmls,'text/xml')
        //获取xml文档的所有子元素
        const rootChildren = root.children;
        //递归方法
        function generate(rootChildren) {
            const d1 = {}
            for (let i = 0; i < rootChildren.length; i++) {
                const child = rootChildren[i];
                if (child.children.length >0) {
                    // 进入递归  递归返回值加入js对象
                    d1[child.nodeName] = generate(child.children);
                    if (child.attributes != null){
                        for (const key in child.attributes) {
                            if (child.attributes[key].value != null){
                                d1[child.nodeName][child.attributes[key].name] = child.attributes[key].value;
                            }
                        }
                    }
                } else {
                    const d2 = {}
                    if (child.childNodes[0] != null){
                        d2['text'] = child.childNodes[0].nodeValue;
                    }else {
                        // 将d2对象text元素赋值为'' 统一对象属性
                        d2['text'] = ''
                    }
                    if (child.attributes != null){
                        // 遍历所有属性 包括自定义属性
                        for (const key in child.attributes) {
                            if (child.attributes[key].value != null){
                                d2[child.attributes[key].name] = child.attributes[key].value;
                            }
                        }
                    }
                    d1[child.nodeName] = d2
                }
            }
            return d1
        }
        return generate(rootChildren);
    }


    transformXml(xml)

json序列化后输出如下

{
    "a":{
        "b":{
            "text":"123",
            "bbb":"这是b标签属性"
        },
        "c":{
            "d":{
                "text":"123",
                "abc":"这是属性"
            },
            "e":{
                "text":"123"
            },
            "ccc":"这是c标签属性",
            "ddd":"这是c标签第二个属性"
        }
    }
}

此方法也可代替之前两种方法 择易使用

四、如果你对自己的代码能力不抱有信心,请使用造好的轮子

fast-xml-parser

  • 12
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值