xpath

testing xpath

HTML

<body>

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

JavaScript

var text = "<bookstore><book category='cooking'>  <title lang='en'>Everyday Italian</title>  <author>Giada De Laurentiis</author>  <year>2005</year>  <price>30.00</price></book><book category='children'>  <title lang='en'>Harry Potter</title>  <author>J K. Rowling</author>  <year>2005</year>  <price>29.99</price></book><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><book category='web'>  <title lang='en'>Learning XML</title>  <author>Erik T. Ray</author>  <year>2003</year>  <price>39.95</price></book></bookstore>";


var parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
 showResult(xmlDoc,"/bookstore/book/author");
 showResult(xmlDoc,"//title");
 showResult(xmlDoc,"//book/author[1]");
 showResult(xmlDoc,"//book[@category=\"web\"]/title");

function showResult(xml,path) {
    var txt = "";
    
    if (xml.evaluate) {
        var nodes = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);
        var result = nodes.iterateNext();
        while (result) {
            txt += result.childNodes[0].nodeValue + "<br>";
            result = nodes.iterateNext();
        } 
    // Code For Internet Explorer
    } else if (window.ActiveXObject || xhttp.responseType == "msxml-document") {
        xml.setProperty("SelectionLanguage", "XPath");
        nodes = xml.selectNodes(path);
        for (i = 0; i < nodes.length; i++) {
            txt += nodes[i].childNodes[0].nodeValue + "<br>";
        }
    }
    document.getElementById('resultado').innerHTML += "<strong>"+path+"</strong><br/>"+txt+"<br>";
}