Search code examples
javascriptxmldomparser

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


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?


Solution

  • 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).