Gmail Filter 导出 XML 在 Apps Script 中解析 apps:property 失败?
数据小陈
结论: 不用去找 http://schemas.google.com/apps/2006 对应的 XSD/schema 文件,也不用联网访问这个地址。它只是一个 XML 命名空间 URI,用来标识 Gmail 扩展里的 apps 元素。Google Apps Script 的 XmlService 能识别命名空间,直接按这个 URI 读取 apps:property 就行。它不会做 XSD 校验,也不会因为该 URL 访问不了就解析失败。
原因: 导出文件里的 xmlns:apps 声明为 http://schemas.google.com/apps/2006,声明的是命名空间,不是可下载的 schema 位置。apps:property 的完整名称由命名空间 URI 和本地名 property 组成,前缀 apps 只是别名。调用 getChildren('property'),或者把 apps:property 当成普通标签名,通常都匹配不到带命名空间的节点。
解析步骤:
- 用
XmlService.parse(xml)解析 XML。 - 用两个 URI 分别拿到
Atom和apps的命名空间对象。 - 从根节点取
Atom命名空间下的entry。 - 在每个
entry里取apps命名空间下的property。 - 读出每个
property的name和value属性,再筛出name为hasTheWord的项。
function parseGmailFilters(xml) {
const doc = XmlService.parse(xml);
const root = doc.getRootElement();
const atomNs = XmlService.getNamespace('http://www.w3.org/2005/Atom');
const appsNs = XmlService.getNamespace('apps', 'http://schemas.google.com/apps/2006');
const entries = root.getChildren('entry', atomNs);
const result = entries.map(entry => {
const props = entry.getChildren('property', appsNs);
const obj = {};
props.forEach(p => {
const nameAttr = p.getAttribute('name');
const valueAttr = p.getAttribute('value');
if (nameAttr) {
obj[nameAttr.getValue()] = valueAttr ? valueAttr.getValue() : '';
}
});
return {
hasTheWord: obj.hasTheWord || '',
all: obj
};
});
Logger.log(JSON.stringify(result, null, 2));
return result;
}
如果 XML 是从 Drive 文件读出来的,可以先取文本再传给函数:
const xml = DriveApp.getFileById('FILE_ID').getBlob().getDataAsString();
const filters = parseGmailFilters(xml);
注意事项:
http://schemas.google.com/apps/2006不是拿来请求的 schema 文档,解析时也不需要访问它。- 匹配命名空间看 URI,不看
apps这个前缀。前缀改了、URI 没变,照样能匹配。 - 以后导出格式如果多了别的命名空间,还是按对应 URI 取节点,别用字符串截取或正则代替命名空间解析。
- 上面的代码只读取并展示
hasTheWord等属性,不会改 Gmail 过滤器,也不依赖非公开 API。
备注:内容仅供参考。
