开发者

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&开发者_运维问答gt;<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 ?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜