Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am new to XML parsing and getting data from XML and I am trying to get the array of href links from the XML which I am getting from API response.

One of the res value is

<?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>

and I am parsing res using DOMParser() 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);

I want the array using querySelectorAll method which will give all the nodeValues of href with <link rel="manifest">.

For example, if the res is

<?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>   

then the querySelectorAll should return ["link1","link2"]

I tried document.querySelectorAll("link[rel='manifest']")) but it gives the array of <link>. I also tried document.querySelectorAll("link[rel='manifest']")[0].attributes['href'].nodeValue but it only gives link1.

How can I get all the nodeValues as array using querySelectorAll instead of passing index and getting one nodeValue at a time?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
356 views
Welcome To Ask or Share your Answers For Others

1 Answer

There could be other ways to do this, but one way would be to turn your NodeList from querySelectorAll to an array then use map to get the properties you are interested in into a new array.

e.g.

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

What this does is:

create an array from document.querySelectorAll("link[rel='manifest']")

then map that array selecting the property you want from each element x => x.attributes['href'].nodeValue (where x is each element in the array we created).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...