Home > Net >  Cannot get child element from parsed XML javascript (google script)
Cannot get child element from parsed XML javascript (google script)

Time:05-12

I am trying to get child node, but it prints null. My code:

function findFile(ICO){
  var fileName = ICO   '.xml';
  const folderFiles = DriveApp.getFolderById('folderID').getFiles();
  while (folderFiles.hasNext()) {
    var folderFile = folderFiles.next();
    if(folderFile.getName() == fileName){
      return folderFile.getId();
      break;
    }
  }
}

function filesearch(ICO){
  var fileId = findFile(ICO);
  var fileFound = DriveApp.getFileById(fileId).getBlob().getDataAsString();
  var rawXml = XmlService.parse(fileFound);
  return rawXml;
}


function parseXML(){
  var text_ICO_txt = '27074358';
  var docXml = filesearch(text_ICO_txt);
  var root = docXml.getRootElement();
  Logger.log(root);
  var child1 = root.getChild('Ares_odpovedi');
  Logger.log(child1);
}

It prints:

[Element: <are:Ares_odpovedi [Namespace: http://wwwinfo.mfcr.cz/ares/xml_doc/schemas/ares/ares_answer_vreo/v_1.0.0]/>]
null

So I tried different variation of Ares_odpovedi (including the whole text after Element:), but child node is null.

XML file:

<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>
  <are:Zakladni_udaje>
...

Could you, please, hint me, how to deal with it?

Thank you in advance!

CodePudding user response:

This answer supposes the modification of your showing script.

When I saw your XML data, it seems that the tag of Ares_odpovedi is the root element. So, for example, when you want to retrieve the element of Odpoved, please modify it as follows.

From:

var root = docXml.getRootElement();
Logger.log(root);
var child1 = root.getChild('Ares_odpovedi');
Logger.log(child1);

To:

var root = docXml.getRootElement();
Logger.log(root);
var child1 = root.getChild('Odpoved', root.getNamespace());
Logger.log(child1);

Reference:

  • Related