Google App Script解析XML无法获取第4层级子元素问题
Google Drive XML深层节点读取问题解决记录
一、相关内容
1. Google Drive中的XML片段
<rDE xmlns="http://ekuatia.set.gov.py/sifen/xsd" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ekuatia.set.gov.py/sifen/xsd siRecep> DE_v150.xsd"> <DE Id="123456789">> <gDtipDE>> <gCamCond> <iCondOpe>2</iCondOpe> <gPagCred> <iCondCred>2</iCondCred> <dDCondCred>Cuota</dDCondCred>
2. 通用读取代码(Google Apps Script)
function getDataFromXML(fileId,Attribute,Child0,Child1,Child2,...,Childn) let data = DriveApp.getFileById(fileId).getBlob().getDataAsString(); let doc = XmlService.parse(data); let root = doc.getRootElement(); let namespace = XmlService.getNamespace('http://ekuatia.set.gov.py/sifen/xsd'); var foods = root.getChild(Child0,namespace).getChild(Child1,namespace).getChild(Child2,namespace).getChildText(Attribute,namespace);
注:Child0只能是'DE',修改后无法正常运行,已确认。
二、问题描述
代码可正常获取第3层级(Child0、Child1、Child2)的元素,但从gPagCred节点开始,添加getChild(Child3, namespace).getChildText(Attribute, namespace)后始终返回null,无法获取更深层级元素。期望实现可访问深层节点数据的通用方法,使用root.getChild(0).getChild(1).getChild(2).getChildText(Attribute)可正常获取第3层级元素,但添加getChild(3)后就返回null。
三、解决方法
代码本身逻辑有效,问题出在未正确配置if else结构(该部分未在上述代码中展示),修正if else结构后,即可正常读取深层节点数据。
内容的提问来源于stack exchange,提问作者William Belini
相关产品推荐
相关产品推荐

