You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中XML属性字符串转键值对失败,求正确实现方法

解决XML转义字符串转键值对数组的问题

你之前的方法之所以没得到预期结果,核心问题是没考虑到属性值里的空格会被拆分,而且没有过滤XML本身的声明、标签名这些无关内容。这里给你一个更可靠的解决方案:

实现思路

  1. 还原转义XML符号:你的字符串里用&lt;和&gt;代替了真实的<和>,第一步要把它们转回来,才能正确解析结构。
  2. 提取目标标签的属性:从XML内容里剥离掉声明、标签头尾,只保留PrintLetterBarcodeData标签的属性列表。
  3. 精准匹配键值对:用正则匹配所有key="value"格式的属性,特意处理了值里包含空格的场景。
  4. 转换为目标结构:把匹配到的键值对转换成对象,再包装成数组得到你要的结果。

完整代码示例

const result = '&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;PrintLetterBarcodeData firstName="John" lastname="joe" gender="M" empNo="32323" city="xxxx" address="xxxxx line22 tn" /&gt;';

// 1. 还原转义的XML标签符号
const decodedXml = result.replace(/&lt;/g, '<').replace(/&gt;/g, '>');

// 2. 提取PrintLetterBarcodeData标签的属性部分
const tagMatch = decodedXml.match(/<PrintLetterBarcodeData\s+(.*?)\/>/);
if (!tagMatch) {
  console.log('未找到目标标签');
  return;
}
const attributesStr = tagMatch[1];

// 3. 匹配所有key="value"格式的键值对,支持值包含空格
const attrRegex = /(\w+)="([^"]+)"/g;
const attrMap = {};
let match;
while ((match = attrRegex.exec(attributesStr)) !== null) {
  attrMap[match[1]] = match[2];
}

// 4. 包装成预期的数组格式
const finalResult = [attrMap];
console.log(finalResult);

输出结果

[
  {
    firstName: "John",
    lastname: "joe",
    gender: "M",
    empNo: "32323",
    city: "xxxx",
    address: "xxxxx line22 tn"
  }
]

这个方案能适配动态变化的示例值,只要目标标签的结构保持一致,就能稳定提取出正确的键值对数组。

内容的提问来源于stack exchange,提问作者user9361329

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:18:22