首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用GatewayScript提取给定数组中的最新日期

使用GatewayScript提取给定数组中的最新日期
EN

Stack Overflow用户
提问于 2021-07-30 03:16:23
回答 1查看 114关注 0票数 0

下面的

示例是传入的XML请求,我需要迭代所有日期,并在输出中使用gatewayScript提取最新更新的日期。

代码语言:javascript
复制
<rsp:response
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rsp="rsp.com/employee/Response/v30"
xmlns:res="res.com/Member/details/v1">
<rsp:period>
    <res:Period>
        <rsp:date>2020-07-06T19:38:39</rsp:date>
    </res:Period>
</rsp:period>
<rsp:period>
    <res:Period>
        <rsp:date>2020-08-07T20:38:39</rsp:date>
    </res:Period>
</rsp:period>
<rsp:period>
    <res:Period>
        <rsp:date>2020-05-06T19:18:39</rsp:date>
    </res:Period>
</rsp:period>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-30 11:16:37

我不太清楚你的问题是什么,希望这能帮上忙。

您可以使用构造函数创建DOM解析器,然后将该XML转换为文档。然后,使用DOM方法获取所需的元素并提取日期,然后遍历它们以查找最新的数据。

例如,下面使用词法比较获得最新的日期,因为日期是ISO 8601格式的。

代码语言:javascript
复制
let xml = `
  <rsp:response
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:rsp="rsp.com/employee/Response/v30"
    xmlns:res="res.com/Member/details/v1">
    <rsp:period>
      <res:Period>
        <rsp:date>2020-07-06T19:38:39</rsp:date>
      </res:Period>
    </rsp:period>
    <rsp:period>
      <res:Period>
        <rsp:date>2020-08-07T20:38:39</rsp:date>
      </res:Period>
    </rsp:period>
    <rsp:period>
      <res:Period>
        <rsp:date>2020-05-06T19:18:39</rsp:date>
      </res:Period>
    </rsp:period>
  </rsp:response>`;

let parser = new DOMParser();
let doc = parser.parseFromString(xml, 'application/xml');
let nodes = Array.from(doc.getElementsByTagName('rsp:date'));
let dates = nodes.map(node => node.textContent);
let latestDate = dates.reduce((latest, date) => date < latest? latest : date);

console.log(latestDate);

HTML和XML的DOM方法有一些重叠,特别是与getElementsByTagName等getElementsByTagName方法重叠。您也可以使用,但这是一种全新的学习语言,支持可能会因所使用的环境而不同。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68585046

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档