Don Holmes
Don Holmes

Reputation: 23

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);  


    }

Upvotes: 0

Views: 379

Answers (3)

Don Holmes
Don Holmes

Reputation: 23

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);

Upvotes: 0

Don Holmes
Don Holmes

Reputation: 23

I also tried this to convert DocumentFragment (resultDoc) to an HTML element (zz)...

var zz=document.createElement("div2");
zz.appendChild(resultDoc);

var evaluator = new XPathEvaluator();

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

yielding exception..."TypeError: Cannot read property 'snapshotLength' of undefined"

Upvotes: 0

Michael Kay
Michael Kay

Reputation: 163342

Try using XPathEvaluator.evaluate()

https://developer.mozilla.org/en-US/docs/Web/API/XPathEvaluator/evaluate

Upvotes: 0

Related Questions