xpath with dom document

11,849

Solution 1

I don't know why did you get this error, but you can change XPathResult.ANY_TYPE to XPathResult.STRING_TYPE and will works (tested in firefox 3.6).

See:

var xmlString = '<form><name>test</name></form>';
var doc = new DOMParser().parseFromString(xmlString,'text/xml');
var result = doc.evaluate('/form/name', doc, null, XPathResult.STRING_TYPE, null);
alert(result.stringValue); // returns 'test'

See in jsfiddle.


DETAILS:

The 4th parameter of method evaluate is a integer where you specify what kind of result do you need (reference). There are many types, as integer, string and any type. This method returns a XPathResult, that has many properties.

You must match the property (numberValue, stringValue) with the property used in evaluate.

I just don't understand why any type didn't work with string value.

Solution 2

XPathResult.ANY_TYPE would return a node set for xpath expression /form/name, so result.stringValue would have trouble converting node set to string. In this case you could use result.iterateNext().textContent

However, an expression like count(/form/name) would return a number value when used with XPathResult.ANY_TYPE and you could use result.numberValue to retrieve the number in that case.

Some more detailed explanation at https://developer.mozilla.org/en/DOM/document.evaluate#Result_types

Share:
11,849
ertan
Author by

ertan

nothing special

Updated on June 05, 2022

Comments

  • ertan
    ertan about 2 years

    I'm trying the find a xml node with xpath query. but i cannot make it working. In firefox result is always "undefined" and chrome throws a error code.

    <script type="text/javascript">
    
    var xmlString = '<form><name>test</name></form>';
    var doc = new DOMParser().parseFromString(xmlString,'text/xml');
    
    var result = doc.evaluate('/form/name', doc, 
                              null, XPathResult.ANY_TYPE, null);
    
    alert(result.stringValue);
    
    </script>
    

    what's wrong with this code ?