Bill
Bill

Reputation: 1477

Using DOMParser in XML to get attribute using JavaScript

I have an XML file that I get from an API and a small section is:

       <Abstract>
            <AbstractText Label="BACKGROUND">A large ...</AbstractText>
            <AbstractText Label="METHODS">We modeled....</AbstractText>
            <AbstractText Label="RESULTS">Mammary glands ... </AbstractText>
            <AbstractText Label="CONCLUSIONS">We report...</AbstractText>
        </Abstract>

My JavaScript code is:

      parser = new DOMParser();
      xmlDoc = parser.parseFromString(response.data, "text/xml");
      const abstracts = xmlDoc.querySelectorAll("AbstractText");

and by using

        abstracts.forEach(a => {         
        abstract_text += a.innerHTML;
        abstract_text += "<br /><br />";
      });

I can read all of the text. My problem is I can't get the Label value. I've tried

    let x = a.attribute("Label").nodeValue;

and

       let x = a.attribute("Label");

both as attribute as attributes .

All help is appreciated.

Upvotes: 1

Views: 2934

Answers (1)

Bravo
Bravo

Reputation: 6254

It's a.getAttribute('Label') you wanted

Here's one way to do it

const xml = `<Abstract>
    <AbstractText Label="BACKGROUND">A large ...</AbstractText>
    <AbstractText Label="METHODS">We modeled....</AbstractText>
    <AbstractText Label="RESULTS">Mammary glands ... </AbstractText>
    <AbstractText Label="CONCLUSIONS">We report...</AbstractText>
</Abstract>`;

parser = new DOMParser();
xmlDoc = parser.parseFromString(xml, "text/xml");
const abstracts = xmlDoc.querySelectorAll("AbstractText");

abstracts.forEach(a => {
  console.log(a.textContent, a.getAttribute('Label'));
});

You could also

a.attributes['Label'].nodeValue
a.attributes.Label.nodeValue
a.attributes['Label'].textContent
a.attributes.Label.textContent

Upvotes: 4

Related Questions