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?
Asked
Active
Viewed 1,584 times
1

Sebastian Simon
- 18,263
- 7
- 55
- 75
-
What do you use for parsing XML? – Peter Aron Zentai Oct 23 '12 at 14:53
-
@PeterAronZentai I am using [xmldom](https://github.com/jindw/xmldom). – Oct 23 '12 at 15:15
-
If you want to do this on the Web instead of Node.js, see [Need to check if processing instruction `` is present in XML or not](/q/74313148/4642212). – Sebastian Simon Nov 05 '22 at 00:56
1 Answers
0
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

Peter Aron Zentai
- 11,482
- 5
- 41
- 71
-
Good code, thanks for it. Speaking of which, do you know any better DOM implementation than xmldom? I searched a lot and ended up picking that one for it was the one that seemed the less bad one. – Oct 23 '12 at 15:29
-
a sorry shake of the head, at least regarding nodejs. this caused us a headache too so ended up with an xml/xslt solution. libxmljs uses the libxml library, and is performant. but using that will limit your nodejs solution to linux (windows does not support node-waf, only node-gyp, and the libxmljs is still the older node-waf based). Plus you lose tier commonality. – Peter Aron Zentai Oct 23 '12 at 15:32