Marco DC
Marco DC

Reputation: 49

get name property from xml tag by getElementsByTagName

I'm trying to get the property "name" from the "stock" tag. Unfortunately, working with getElementsByTagName I did not find the way and, investigating different levels of child nodes, I only retrieved sub tags (as in the code example). Can someone help me?

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var parser, xmlDoc;
var text = "<bookstore><book>" +
"<title>Everyday Italian</title>" +
"<stock name=\"Susceptible Population S\"><eqn>80</eqn></stock>" +
"<year>2005</year>" +
"</book></bookstore>";

parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
var a = xmlDoc.getElementsByTagName("stock")[0].childNodes[0].childNodes[0];
var b = "ciro";
document.getElementById("demo").innerHTML = a.nodeValue;

</script>

</body>
</html>

Upvotes: 1

Views: 446

Answers (2)

Marco DC
Marco DC

Reputation: 49

Thanks again for your help. Unfortunately I experienced a new problem.

The same code does not work if I add just a row to my xml:

"<xmile version="1.0" xmlns="http://docs.oasis-open.org/xmile/ns/XMILE/v1.0" xmlns:isee="http://iseesystems.com/XMILE">"

It seems that the problem is the keyword "xmlns". Indeed if I change it in "somevar" everything's works fine.

Can you, or someone else, help me in this additional problem.

P.S.

the xmlDoc = parser.parseFromString(text,"text/xml");is created in the right way but the xmlDoc.evaluate fails in finding the desired tag

Upvotes: 0

Jack Fleeting
Jack Fleeting

Reputation: 24930

Try changing your script (after xmlDoc)

let a = xmlDoc.evaluate( '//stock/@name', xmlDoc, null, XPathResult.ANY_TYPE, null );
let newVal = a.iterateNext().value

document.getElementById("demo").innerHTML = newVal;

and see if it works.

Upvotes: 1

Related Questions