views:

109

answers:

3

I was experimenting around with XPath, basically I'm trying to load a HTML page using XMLHttpRequest and select an element inside it from its XPath.

Here's my code (Greasemonkey/Js):

GM_xmlhttpRequest({
method: 'GET',
url: url,
headers: {
    'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
    'Accept': 'application/atom+xml,application/xml,text/xml',
},
onload: function(responseDetails)
{
    var rs = document.evaluate("/html/body/div",responseDetails.responseText,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var n = rs.snapshotItem(0);
    alert(n.innerHTML);
}});

But it isn't working.

This is the error I'm getting:

uncaught exception: [Exception... "Could not convert JavaScript argument arg 1
[nsIDOMXPathEvaluator.evaluate]" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" 
location: "JS frame :: file:///C:/Documents%20and%20Settings/Admin/Application%20Data
/Mozilla/Firefox/Profiles/mq3w8kw4.default/extensions/%7Be4a8a97b-f2ed-450b-
b12d-ee082ba24781%7D/components/greasemonkey.js :: anonymous :: line 587" data: no] 
A: 

Take a look at these hits on Google - you might find an answer there.

Jim Garrison
I've already tried google.. That's why I'm here :D..
A User
+1  A: 

You are trying to run an XPath query on a string, responseText, try responseXML instead.

Still, I'm guessing that unless the web page you are loading has completely valid XHTML, this too will fail. If you want to run XPath queries on mangled HTML, try loading loading it in an iframe, then use iframe.contentDocument.evaluate

MooGoo
yah, responseXML doesn't work, I guess the page isn't valid. I don't like the idea of using an iframe. Maybe regexp might be a better way of extracting the value I need w/o using xpath. Thanks for you answer.
A User
A: 

This is what you are looking for: Fetching xml with GM_xmlhttpRequest

w35l3y