I am trying to use jQuery parseXml in node.js
I am getting this error:
Error: Invalid XML: <?xml version="1.0"...
But the problem is not in the XML
The problem is in node-jquery.js:
parseXML: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
var xml, tmp;
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
To put it simply, in node.js, there is no DOMParser, and there is no ActiveXObject( "Microsoft.XMLDOM" )
Since I am working in windows, I would expect ActiveXObject to work, but no, it does not, the actual error swallowed by jQuery is not an invalid XML it is that ActiveXObject is not defined:
ReferenceError: ActiveXObject is not defined
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:
Any workarounds for this? How can I make jQuery.parseXML work?
I've had great success using xmldom. Take a look. It seems to parse an xml just like you would expect
$.parseXML
to. I was also having problems with the jquery parser and switched to this one after trying a bunch out.If you want to continue to use
jQuery.parseXML
without having to make any changes to your code (like if you want to be able to run the same javascript both client-side and in Node.js), it is easy to set that up. The xmldom module mentioned in M. Laing’s answer exposes aDOMParser
constructor that jQuery can use the same way it uses DOMParser in the browser. Here’s how to do so:First, install xmldom:
Assuming you already have jQuery 2.1.x or greater working in Node.js (for instructions on setting that up, see the README in this repository), you can now just require xmldom and expose its
DOMParser
constructor as a global:jQuery will now be able to successfully
parseXML
.That looks to be something that would have to be implemented into the core of nodejs. I would suggest using a module designed to parse XML.
https://github.com/Leonidas-from-XIV/node-xml2js
Do you need jQuery.parseXML to work, like are you trying to write code to cross into the browser and run on the server?
You could probably expose node-xml2js in the browser with browserify
There is also libxmljs which seems to be more XML like than node-xml2js.