xpath with dom document

ertan picture ertan · Aug 29, 2010 · Viewed 11.9k times · Source

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 ?

Answer

Topera picture Topera · Aug 29, 2010

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.