Xpath with dom document

I am trying to find an xml node with an xpath request. but I can't get it to work. As a result, firefox is always "undefined", and chrome produces an 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 is wrong with this code?

+6
javascript dom xml xpath document.evaluate
source share
2 answers

I donโ€™t know why you got this error, but you can change XPathResult.ANY_TYPE to XPathResult.STRING_TYPE and will work (tested in firefox 3.6).

Cm:

 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 jsfiddle .


DETAILS:

The 4th parameter of the evaluate method is an integer in which you indicate what result you need ( link ). There are many types , like integer, string, and any type. This method returns an XPathResult that has many properties.

You must map the property (numberValue, stringValue) to the property used in the evaluation.

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

+6
source share

XPathResult.ANY_TYPE will return the node value for the xpath /form/name expression, so result.stringValue will have problems converting the node to a string. In this case, you can use result.iterateNext().textContent

However, an expression like count(/form/name) will return a numeric value when used with XPathResult.ANY_TYPE , and you can use result.numberValue to extract the number in this case.

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

+2
source share

All Articles