Skip to content
Advertisement

Parse XML from Google Drive in Javascript (Google Scripts) [duplicate]

I would like to ask you, please, how to parse this XML file? I would like to work with a couple of child nodes.

<are:Ares_odpovedi xmlns:are="http://wwwinfo.mfcr.cz/ares/xml_doc/schemas/ares/ares_answer_vreo/v_1.0.0" odpoved_datum_cas="2022-05-09T15:00:10" odpoved_pocet="1" odpoved_typ="Vypis_VREO" vystup_format="XML" xslt="klient" validation_XSLT="http://wwwinfo.mfcr.cz/ares/xml_doc/schemas/ares/ares_odpovedi.xsl" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://wwwinfo.mfcr.cz/ares/xml_doc/schemas/ares/ares_answer_vreo/v_1.0.0 http://wwwinfo.mfcr.cz/ares/xml_doc/schemas/ares/ares_answer_vreo/v_1.0.0/ares_answer_vreo.xsd" Id="ares">
<are:Odpoved>
 <are:Pomocne_ID>0</are:Pomocne_ID>
 <are:Vysledek_hledani>
  <are:Kod>1</are:Kod>
 </are:Vysledek_hledani>
 <are:Pocet_zaznamu>1</are:Pocet_zaznamu>
 <are:Vypis_VREO>
  <are:Uvod>
   <are:Nadpis>Výpis z veřejného rejstříku v ARES - elektronický opis</are:Nadpis>
   <are:Aktualizace_DB>2022-05-09</are:Aktualizace_DB>
   <are:Datum_vypisu>2022-05-09</are:Datum_vypisu>
   <are:Cas_vypisu>15:00:09</are:Cas_vypisu>
   <are:Typ_vypisu>aktualni</are:Typ_vypisu>
  </are:Uvod>
  ...

My code:

var xml = UrlFetchApp.fetch("https://drive.google.com/file/d/[fileID]").getContentText();
var data = XmlService.parse(xml);
Logger.log(data.type);

And I receive error:

Exception: Error on line 1257: The element type "meta" must be terminated by the matching end-tag "</meta>".

Even though there are no tags “meta” and the last row in xml document is 1008.

Thank you in advance!

Advertisement

Answer

Replace

var xml = UrlFetchApp.fetch("https://drive.google.com/file/d/[fileID]").getContentText();

by

var xml = DriveApp.getFileById(fileID).getBlob().getDataAsString();

As your script is using UrlFetchApp to retrieve a Google Drive file using a URL of the form https://drive.google.com/file/d/[fileID] your script is getting the HTML content of the file preview.

There are two possible paths, use a URL of the form https://drive.google.com/uc?export=download&id=fileID or use the Google Drive Service i.e. DriveApp.getFileById(fileID).getBlob().getDataAsString().

If you will go for using the UrlFetchApp you should make the file public or to pass the appropriate credentials., considering this the most convenient solution is to use the Google Drive Service.

Resources

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement