Jump to content

101: w3 examples; xpath /price v/s /price/text()


snowsalt

Recommended Posts

There are two paths in xpath examples which are treated in different fashion. I don't understand why.path="/bookstore/book/price/text()"andpath="/bookstore/book[price>35]/price";In the first example, nodes/values(?) are inspected this way:===============================================var nodes=xml.evaluate(path, xml, null, XPathResult.ANY_TYPE,null);var result=nodes.iterateNext();while (result) { document.write(result.nodeValue + "<br />"); result=nodes.iterateNext(); }In the second example:================================================var nodes=xml.evaluate(path, xml, null, XPathResult.ANY_TYPE,null);var result=nodes.iterateNext();while (result) { document.write(result.childNodes[0].nodeValue); document.write("<br />"); result=nodes.iterateNext(); }The difference are in these two lines document.write(result.nodeValue + "<br />");and document.write(result.childNodes[0].nodeValue);Would someone please explain this. Thank you.

Link to comment
Share on other sites

/bookstore/book/price/text() selects nodes of type "text", while /bookstore/book[price>35]/price selects nodes of type "element". By definition for nodes of type "element" in the W3C DOM the nodeValue property is null. There is however a property named "textContent" you can access so instead of document.write(result.childNodes[0].nodeValue);I would suggest to simply use document.write(result.textContent);In more detail: With

<bookstore>  <book>	 <price>10</price>  </book></bookstore>

the "price" element has one child node, a "text" node with nodeValue "10". The nodeValue of the "price" element node itself is (by definition) null so to access the contents of the price element you either need to access the textContent property or you need to access the "text" child node with result.firstChild or result.childNodes[0] and then the nodeValue property.I would strongly suggest to write XPath expressions that select element nodes and not text nodes, unless you have mixed contents (i.e. elements and text mixed together) and you are really interested in a particular text node.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...