如何根据rel='manifest' in <link>获取所有href nodeValue

How to get all the href nodeValue based on rel='manifest' in <link>

我不熟悉 XML 从 XML 解析和获取数据,我正在尝试从 XML 获取 href 链接数组来自 API 回复。

其中一个 res 值是

<?xml version="1.0" encoding="UTF-8"?>
    <manifests
        xmlns="http://www.xyz.ca/ws/manifest-v8">
        <link rel="manifest" href="link1" media-type="application/vnd.cpc.manifest-v8+xml"/>
        <link rel="artifact" href="artifact1" media-type="application/vnd.cpc.manifest-v8+xml"/>
        <link rel="manifest" href="link2" media-type="application/vnd.cpc.manifest-v8+xml"/>
    </manifests>

我正在使用 DOMParser() 解析 res as

const document =  new DOMParser().parseFromString(res, 'application/xml');
 console.log((document.querySelectorAll("link[rel='manifest']")).length);
 console.log(document.querySelectorAll("link[rel='manifest']")[0].attributes['href'].nodeValue);

我想要使用 querySelectorAll 方法的数组,它会给出 href 的所有 nodeValues<link rel="manifest">

例如,如果 res

<?xml version="1.0" encoding="UTF-8"?>
    <manifests
        xmlns="http://www.xyz.ca/ws/manifest-v8">
        <link rel="manifest" href="link1" media-type="application/vnd.cpc.manifest-v8+xml"/>
        <link rel="artifact" href="artifact1" media-type="application/vnd.cpc.manifest-v8+xml"/>
        <link rel="manifest" href="link2" media-type="application/vnd.cpc.manifest-v8+xml"/>
    </manifests>   

那么 querySelectorAll 应该 return ["link1","link2"]

我试过 document.querySelectorAll("link[rel='manifest']")) 但它给出了 <link> 的数组。 我也试过 document.querySelectorAll("link[rel='manifest']")[0].attributes['href'].nodeValue 但它只给出 link1.

如何使用 querySelectorAll 获取所有节点值作为数组而不是传递索引并一次获取一个节点值?

可能还有其他方法可以做到这一点,但一种方法是将您的 NodeListquerySelectorAll 变为 array,然后使用 map 获得您感兴趣的属性放入一个新数组中。

例如

let hrefs = Array.from(document.querySelectorAll("link[rel='manifest']")).map(x => x.attributes['href'].nodeValue)

它的作用是:

document.querySelectorAll("link[rel='manifest']")

创建数组

然后映射该数组,从每个元素 x => x.attributes['href'].nodeValue 中选择您想要的 属性(其中 x 是我们创建的数组中的每个元素)。