11

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 ?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
ertan
  • 645
  • 1
  • 7
  • 14

2 Answers2

13

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.

Topera
  • 12,223
  • 15
  • 67
  • 104
3

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

Aurimas
  • 311
  • 2
  • 10