Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing XML with default namespace using xPath in javascript

I need to create an XML xPath parser. All parsing has to happen on client side (using javascript). I created an javascript that does this, and everything looks OK until default namespaces come into play. I simply can't query XML that has default namespace.

I created an example code on fiddle. In xmlString is XML string received from server. In xPathString is query done on received XML.

Here are some scenarios:

  1. http://jsfiddle.net/BF34q/1/ - no namespaces - everything works OK
  2. http://jsfiddle.net/BF34q/2/ - ns namespace added. element has ns: prefix. xPath uses this prefix - OK
  3. http://jsfiddle.net/BF34q/3/ - default namespace used - not sure how to configure xPathString.

Note that others will use this parser, so I would really like to avoid solutions like

var xPathString = "//*[local-name()='book']";

and enable them to parse it using simple xPath expressions. I wonder if it is possible to assign default namespace prefix in javascript?

Note: The example provided on fiddle will not work in IE.

like image 876
dugokontov Avatar asked Oct 16 '25 04:10

dugokontov


1 Answers

I think there are three ways to do this:

  1. Use //*[local-name()='book'] syntax for accessing nodes
  2. Convert XML to string, remove default namespace using RegExp, convert it back to XML
  3. For XML files where you know namespaces in advance, you can create your own namespace resolver, which will allow you to use your own prefix for default namespace.

This can be achieved like this:

function nsResolver(prefix) {
    switch (prefix) {
        case 'xhtml':
            return 'http://www.w3.org/1999/xhtml';
        case 'mathml':
            return 'http://www.w3.org/1998/Math/MathML';
        default:
            return 'http://example.com/domain';
    }
}
xml.evaluate('//myPrefix:book', xml, nsResolver, XPathResult.ANY_TYPE, null);
like image 155
dugokontov Avatar answered Oct 18 '25 20:10

dugokontov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!