简体   繁体   中英

Childnodes multiple javascript XML

Can't get chosen child when trying to pull out of XML - in this case it is author:

<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>

I can't get the javascript script to display my chosen author. Meaning that if I do this.

txt=xmlDoc.getElementsByTagName("title")[2].childNodes[0].nodeValue;
document.write("<p>"+txt);

I get 'James McGovern'. But

txt=xmlDoc.getElementsByTagName("title")[2].childNodes[1].nodeValue;
document.write("<p>"+txt);

Will not give me 'Per Bothner'. How can I make this possible?

while i'm wondering how you obtained your result, too ... the childNodes array does not only contain elements but (among others) also text nodes, namely line separators (CR/LF). therefore you'd have to iterate through the array checking the node type of each entry. a better choice is using xpath to select the interesting elements, this article should get you started.

specifically, /book/author will select exactly the, well, author nodes in document order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM