cheeriojs 迭代 xml 响应

cheeriojs iterate over xml response

假设我有一个来自如下请求的 xml 响应:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="/xsl/someExcelSheet.xsl"?>
<events>
  <event onair="true">
    <type>Live</type>
    <title>Nyhederne - 1/1</title>
    <airtime>09:30:02.13</airtime>
    <id>58529</id>
  </event>
  <event onair="false">
    <type>PrimaryVideo</type>
    <title>MTV1</title>
    <airtime>09:35:02.13</airtime>
    <id>58532</id>
  </event>
  ...

如何使用 cheeriojs 从中提取数据?

正在做

  request(url, (error, response, xml) => {
    if (!error && response.statusCode == 200) {
      const $ = cheerio.load(xml, {
        xmlMode: true,
        decodeEntities: true,
        withStartIndices: false,
        withEndIndices: false,
      })

正在尝试

> $('events')
LoadedCheerio(1) [Element, options: {…}, _root: LoadedCheerio(1), prevObject: LoadedCheerio(1)]
> $('event')
LoadedCheerio(468) [Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, Element, …]

但不知道如何使用它。想要获取 events 中的所有 event 并对其进行迭代并阅读 <type><title> 等标签中的文本。

我最后做的是

const rows: string[][] = $('event')
  .text()
  .split(/\n/)
  .map((str) => str.trim())
  .join('\n')
  .split(/\n{2,}/g)
  .reduce((acc, str) => [...acc, str.split(/\n/)], [])

但一定有更好的方法,我希望有人愿意向我解释一下?

像这样的事情应该让你开始:

$('event').get().map(event => {
  return {
    type: $(event).find('type').text(),
    title: $(event).find('title').text(),
    // more props
  }
})