Search code examples
xmldocument.evaluate

XML/XSL evaluate() on a DocumentFragment?


For whatever reason, if I feed in the source XML, evaluate does it's thing. However, if I transform XML using the stylesheet and it's a DocumentFragment, it goes to the alert("no"). Does anybody have an idea what might be going on? Maybe need to convert the DocumentFragment before running evaluate? But to what? Thank you so much.

doc_trans=xsltProcessor.transformToFragment(doc_xml_source, document);

//var resultDoc=doc_xnl_source;
var resultDoc=doc_trans;

//var path = "/catalog/cd/title"
path="/html/body/table//row";

if (resultDoc.evaluate) {
    alert("yes");
    var nodes = rDoc.evaluate(path, resultDoc, null, XPathResult.ANY_TYPE, null);
    var result = nodes.iterateNext();
    while (result) {
    alert(result.childNodes[0].nodeValue);
        txt += result.childNodes[0].nodeValue + "<br>";
        result = nodes.iterateNext();
    } 
    } else {
 alert("no");


var evaluator = new XPathEvaluator();

//DocumentFragment not a valid node type exception thrown here...

var resulty = evaluator.evaluate("//tbody/tr", resultDoc, null, 
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);

alert( resulty.snapshotLength);  


    }

Solution

  • DocumentFragment shares most of the methods with NodeList, so methods like querySelector and querySelectorAll, firstChild etc with the resulting DocumentFragment.

    I wanted to find the number of rows in the transformed document (A DocumentFragment) so used querySelector instead of evaluate...

    var allDivs = resultDoc.querySelectorAll('tr');
    
    alert(allDivs.length);