I have an XML file that contains processing instructions in the form of <?myinst contents ?>
. I need to get all of them in a collection, with a single DOM query, if possible, using XMLDOM on Node.js. Is this possible without having the iterate over all the tree?
You have to iterate over the tree with xml-dom. The implementation you pointed to actually uses full iteration for even the getElementByID, or for other selector methods. Better implementations would use tagName and id caches... If your aim is to full tier compatibility (browser and nodejs code commonality) you simply don't have other options then a recursion based filter, something like this.
function _visitNode(node,callback){
if(callback(node)){
return true;
}
if(node = node.firstChild){
do{
if(_visitNode(node,callback)){return true}
}while(node=node.nextSibling)
}
}
function getPIs(rootNode){
var ls = [];
_visitNode(rootNode, function(node){
if(node !== rootNode && node.nodeType == 7) {
ls.push(node);
return true;
}
});
return ls;
}
We use libxmljs and xslt for selecting things but just for PIs it might be an overkill... HTH