Is it possible to get all the processing instruction elements using XMLDOM?

1.6k views Asked by At

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?

1

There are 1 answers

2
Peter Aron Zentai On BEST ANSWER

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