Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath with dom document

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 ?

like image 878
ertan Avatar asked Aug 29 '10 21:08

ertan


2 Answers

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.

like image 175
Topera Avatar answered Nov 15 '22 15:11

Topera


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

like image 38
Aurimas Avatar answered Nov 15 '22 13:11

Aurimas