Search code examples
jqueryxmlsizzle

Using Sizzle to parse XML files?


I created a library for parsing and extracting information from a set of XML files that uses jQuery. So it's pretty simple to do things like this:

$xml = $($.parseXML(xmlText))
title = $xml.find(".title>longName").text()

I then realized that my little library shouldn't need a dependency on all of jQuery, and that I could probably get what I wanted just using the Sizzle library, since that's where jQuery's .find method comes from. However, I am having trouble right out of the gate.

Sizzle doesn't seem to have a parseXML function. Is there any way to pass in a chunk of XML text and get back an object that can be searched on?

I noticed that you could pass in a context to Sizzle's find function. However, Sizzle.find(".title", xmlText) failed to find anything.

Any ideas? Is it possible to use Sizzle to parse XML in the same way that I was using jQuery above?

Note: I want to be able to run this in a headless manner or on Node, so I'd prefer not to use browser dependencies like DOMParser.


Solution

  • You could just use parseXML from jQuery:

    function parseXML( 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 ) {
            throw new Error( "Invalid XML: " + data );
        }
        return xml;
    }