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
相关产品推荐
相关产品推荐

