首页 > 解决方案 > Google Apps 脚本 XML 解释错误

问题描述

我正在尝试将 XML 导入 Google Apps 脚本进行解析,我得到以下信息:

例外:与元素类型“文档”关联的属性“xsi:schemaLocation”的前缀“xsi”未绑定。

这是我运行的代码:

function combinePaths() {
  //1. Get xml:
  var earthFile = DriveApp.getFileById("1Pa994sHM-B8gAFxmrQk0Q3CWeQm1-I61");
  //2. Get xml string from xml:
  /*We must change the type of the file to pull it in as an editable set of data.*/
  var earthFileName = earthFile.getName();
  var earthBlob = earthFile.getAs("text/xml");
  var earthString = earthBlob.getDataAsString();
  var earthContent = XmlService.parse(earthString);

错误在最后一行抛出。该错误似乎与我尝试导入的特定 XML 的构造有关。然而,在比较一个没有抛出此错误的 XML 和一个有此错误的 XML 时,至少在文档的总体结构的顺序上没有区别,即:

<Xml><Document><name><description> </Xml></Document></name></description> 

ETC...

有没有人遇到过类似的事情?是否有任何资源可以让我更清楚地确定此错误的含义?

标签: xmlgoogle-apps-script

解决方案


Yes, pretty much everyone who has used XML much in the last twenty years has run into something similar. There is a start-tag in the document of the form

<Document xsi:schemaLocation="...">

and it almost certainly appears at the very top of the file. But there is no in-scope namespace declaration binding the prefix xsi to a namespace. So neither the parser nor any downstream app knows what namespace the 'schemaLocation' attribute is in; most XML parsers treat this as a fatal error.

Since 'xsi' is a conventional prefix for the XSD Instance namespace, and 'schemaLocation' is a frequently used attribute in that namespace, it is likely (but not completely certain) that the missing namespace declaration should have the form

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

Contact whoever is generating the XML document you are trying to consume, tell them their output is violating the rules of the XML namespaces spec, and ask them politely to fix it. If you are generating the XML document yourself, spend a little time searching for, reading, and understanding some tutorial information on XML namespaces and how to declare namespace prefixes. (Actually, you probably want to do this anyway, since your inability to interpret the error message signals that you have a gap in your XML knowledge where namespace declarations should be.)

On another topic ... At first glance your code appears to be asking to load the data to a variable as XML, and then asking that it be re-serialized and re-parsed. Is this re-serialization and re-parsing necessary? If so, the error might possibly lie with the serialization of the Blob as XML, and you might wish to report a bug in the serialization method.


推荐阅读