Javascript 如何基于rel=';舱单';在<;链接>;
我不熟悉XML解析和从XML获取数据,我正在尝试从API响应中获得的XML中获取Javascript 如何基于rel=';舱单';在<;链接>;,javascript,xml,domparser,Javascript,Xml,Domparser,我不熟悉XML解析和从XML获取数据,我正在尝试从API响应中获得的XML中获取href链接数组 res值之一为 <?xml version="1.0" encoding="UTF-8"?> <manifests xmlns="http://www.xyz.ca/ws/manifest-v8"> <link rel="manifest" href=
href
链接数组
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
方法,该方法将使用
提供href
的所有节点值
例如,如果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>
然后查询选择器all
应返回[“link1”、“link2”]
我尝试了document.querySelectorAll(“link[rel='manifest'])
,但它给出了
的数组。
我还尝试了document.querySelectorAll(“link[rel='manifest']”[0]。attributes['href'].nodeValue
,但它只提供link1
如何使用querySelectorAll获取所有节点值作为数组,而不是通过索引一次获取一个节点值?还有其他方法可以做到这一点,但是一种方法是将NodeList
从querySelectorAll
转换为array
,然后使用map
将感兴趣的属性转换为新数组
e、 g
它的作用是:
从document.querySelectorAll(“link[rel='manifest'])创建数组
然后映射该数组,从每个元素中选择所需的属性x=>x.attributes['href'].nodeValue
(其中x
是我们创建的数组中的每个元素)。我相信您可以直接在返回的节点列表上调用.map()
@ScottMarcus-hmm我不这么认为,NodeList没有实现map-即未捕获的TypeError:document.querySelectorAll(…).map不是一个函数,因为它现在确实实现了.forEach()
,我想.map()
也可以。@ScottMarcus啊,我明白你的意思了……问题是节点列表不共享阵列原型-所以虽然它有forEach,但它不支持阵列方法。
<?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>
let hrefs = Array.from(document.querySelectorAll("link[rel='manifest']")).map(x => x.attributes['href'].nodeValue)