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

Google App Script解析XML:为每个值添加对应键属性的需求

Google App Script XML解析:生成带键值对的结构化对象数组

先明确你的需求场景:

示例XML数据

<root>
  <item key="name">Alice</item>
  <item key="age">30</item>
  <item key="city">New York</item>
</root>

当前代码输出(拼接字符串)

Alice30New York

期望输出(结构化对象数组)

[
  { key: "name", value: "Alice" },
  { key: "age", value: "30" },
  { key: "city", value: "New York" }
]

修改后的Google App Script代码

function parseXmlToStructuredArray(xmlString) {
  // 解析XML字符串
  const document = XmlService.parse(xmlString);
  const root = document.getRootElement();
  
  // 获取所有子节点
  const items = root.getChildren();
  const resultArray = [];
  
  // 遍历节点提取键值对
  items.forEach(item => {
    const key = item.getAttribute('key').getValue();
    const value = item.getText();
    resultArray.push({ key, value });
  });
  
  return resultArray;
}

// 测试用例
function testParse() {
  const testXml = `<root>
  <item key="name">Alice</item>
  <item key="age">30</item>
  <item key="city">New York</item>
</root>`;
  Logger.log(parseXmlToStructuredArray(testXml));
}

关键说明

  • 用XmlService.parse()处理XML是Google App Script官方推荐的方式,避免原生DOM解析的兼容性问题
  • 如果你的子节点有特定标签名(比如不是item),可以把root.getChildren()改成root.getChildren('你的标签名')来精准筛选
  • 若存在没有key属性的节点,可以加个判断:const key = item.getAttribute('key')?.getValue() || 'unknown',避免报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 03:09:58