最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - xpath with dom document - Stack Overflow

programmeradmin0浏览0评论

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 ?

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 ?

Share Improve this question edited Sep 24, 2015 at 17:45 sideshowbarker 88.1k29 gold badges214 silver badges211 bronze badges asked Aug 29, 2010 at 21:03 ertanertan 7051 gold badge7 silver badges15 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 14

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)

  1. 暂无评论