【问题标题】:Working with an API which return a xml not patterned使用返回未模式化 xml 的 API
【发布时间】:2017-09-06 21:48:10
【问题描述】:

我正在请求一个 API 向其发送要搜索的单词,然后从 API 中检索数据。不幸的是,xml 树没有被模式化,所以我需要使用 if 语句来解析每个单词的 xml 文件。 像这样:

    if((JSON.stringify(result["entry_list"]["entry"][0]["sound"][0]["wav"][0])) !== undefined) {
        ...
        ...
       }

我需要检查xml中是否有这些元素,否则我会报错:“TypeError: Cannot read property '0' of undefined”。

问题在于,如果我没有成功,所以我想知道在这种情况下领导的正确方法是什么?

提前致谢!

enter image description here

enter image description here

【问题讨论】:

  • 显示返回的 xml 示例
  • 请提供回复,以便我们为您的陈述提供帮助
  • @Sag1v 我附上了两个打印屏幕,所以我认为它们可以显示正在发生的事情。谢谢。

标签: javascript node.js xml express xml2js


【解决方案1】:

您可以使用object-get,这样如果路径不存在,它就不会抛出错误。

const objectGet = require('object-get')

const colour = objectGet(mammal, 'fur.appearance.colour')
const text = objectGet(el, 'children[2].children[1].children[1].textContent')

然后像if (text) {}一样检查

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多