简体   繁体   English

仅使用内置 JavaScript 函数解析 XML 文件

[英]Parsing XML file using only built-in JavaScript functions

I'm a beginner in coding and I'm trying to parse an XML file, hosted on GitHub , using JavaScript, to extract, for instance, the information contained in the <author> node nested in the <book id="bk102"> node.我是编码初学者,我正在尝试使用 JavaScript 解析托管在 GitHub 上的 XML 文件,以提取例如嵌套在<book id="bk102">中的<author>节点中包含的信息<book id="bk102">节点。

I'm aware there are several similar questions in Stackoverflow, I read many of them but what I am trying to do is to extract data from the above-mentioned XML file, using only built-in JavaScript functions.我知道 Stackoverflow 中有几个类似的问题,我阅读了很多,但我想要做的是仅使用内置的 JavaScript 函数从上述 XML 文件中提取数据。

Honestly, I don't know if it is even possible but I'll explain a bit more in details what I tried to do in order to give you the whole picture.老实说,我不知道这是否可能,但我会更详细地解释我试图做的事情,以便为您提供全貌。

Why I can use only JS built-in functions?为什么我只能使用JS内置函数?

I'm developing a dynamic survey form using a data collection platform called Fulcrum .我正在使用名为Fulcrum的数据收集平台开发动态调查表。

Fulcrum allows to write JavaScript code (with some custom functions) in its 'Data events' module in order to interact with the fields and calculations contained in the survey form itself. Fulcrum 允许在其“数据事件”模块中编写 JavaScript 代码(带有一些自定义函数),以便与调查表单本身中包含的字段和计算进行交互。

The 'Data events' module in Fulcrum doesn't allow me to install additional packages. Fulcrum 中的“数据事件”模块不允许我安装其他软件包。 For this reason, I cannot install, for example, xml-js library, as suggested here , to use the built-in JavaScript JSON functions or I cannot use DOMParser() interface, among others, since Fulcrum wouldn't recognize it.出于这个原因,我无法安装,例如, 这里建议的xml-js库,以使用内置的 JavaScript JSON 函数,或者我无法使用DOMParser()接口等,因为 Fulcrum 无法识别它。

From where I started?我从哪里开始?

Reading Fulcrum documentation, I found out I can use acustom function called REQUEST and I referred to the following example.阅读 Fulcrum 文档后,我发现我可以使用一个名为 REQUEST自定义函数,并参考了以下示例。 The Fulcrum custom functions are identified with CAPITAL LETTERS. Fulcrum 自定义函数用大写字母标识。

// This example looks up the place name from OpenStreetMap when the location changes and fills in a text
// field with the place name. Replace 'place_name' below with a text field on your form.

ON('change-geometry', function(event) {
  var options = {
    url: 'https://nominatim.openstreetmap.org/search/' + LATITUDE() + ',' + LONGITUDE(),
    qs: {
      format: 'json',
      polygon: 1,
      addressdetails: 1
    }
  };

  REQUEST(options, function(error, response, body) {
    if (error) {
      ALERT('Error with request: ' + INSPECT(error));
    } else {
      var data = JSON.parse(body);
      if (data.length) {
        SETVALUE('place_name', data[0].display_name);
      }
    }
  });
});

The only issue here is that this example reads form a JSON file, while I need to read from a XML file.这里唯一的问题是这个例子从一个 JSON 文件中读取,而我需要从一个 XML 文件中读取。

What I tried?我尝试了什么?

I tried to edit the function in the example to make it work with an XML file.我尝试编辑示例中的函数以使其适用于 XML 文件。 This is how I modified it.我就是这样修改的。

ON('click', 'import_xml', function(event) {
  var options = {
    url: 'https://gist.githubusercontent.com/Ram-N/5189462/raw/46db0b43ad7bf9cbd32a8932f3ab981bd4b4da7c/books.xml',
    qs: {
      format: 'xml'
    }
  };

  REQUEST(options, function(error, response, body) {
    if (error) {
      ALERT('Error with request: ' + INSPECT(error));
    } else {
      var data = body;
      if (data.length) {
        SETVALUE('test_field_xml', data);
      }
    }
  });
});

And it works!它有效! Partially... When I click the import_xml hyperlink (refer to 1 below), I'm able to import the whole body of the XML file in the test_field_xml field (refer to 2 below) but I dont' really know how to extract only the information contained in the <author> node nested in the <book id="bk102"> node.部分...当我单击import_xml超链接(请参阅下面的 1)时,我可以在test_field_xml字段中导入整个 XML 文件(请参阅下面的 2),但我真的不知道如何只提取<author>节点中包含的信息嵌套在<book id="bk102">节点中。

在此处输入图片说明

Any advice on how to proceed would be extremely helpful.关于如何进行的任何建议都会非常有帮助。 Thank you, Stefano.谢谢你,斯特凡诺。


EDIT1:编辑1:

I think I found a very "homemade" and partial solution, also not very practical or nice but it works.我想我找到了一个非常“自制”的部分解决方案,也不是很实用或很好,但它有效。 I edited the code above as shown below:我编辑了上面的代码,如下所示:

ON('click', 'import_xml', function(event) {
  var options = {
    url: 'https://gist.githubusercontent.com/Ram-N/5189462/raw/46db0b43ad7bf9cbd32a8932f3ab981bd4b4da7c/books.xml',
    qs: {
      format: 'xml'
    }
  };

  REQUEST(options, function(error, response, body) {
    if (error) {
      ALERT('Error with request: ' + INSPECT(error));
    } else {
      var data = body;
      var test1 = body.substring(
            body.lastIndexOf('<book id="bk102">') + 24, 
            body.lastIndexOf('<book id="bk103">') - 15
        );
      var test2 = test1.substring(
            test1.lastIndexOf('<author>') + 8, 
            test1.lastIndexOf('</author>') - 0
        );     
      if (data.length) {
        SETVALUE('test_field_xml', test2);
      }
    }
  });
});

In your opinion, could this be done in a better and more efficient way?在您看来,这可以以更好、更有效的方式完成吗?

You have said you are allowed to write Javascript code, but that you can't install additional Javascript packages.您说过您可以编写 Javascript 代码,但不能安装其他 Javascript 包。 So the answer is to download an open-source XML parser written in Javascript and add it to your code as if it was part of the code you had written yourself.因此,答案是下载一个用 Javascript 编写的开源 XML 解析器,并将其添加到您的代码中,就好像它是您自己编写的代码的一部分一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM