【发布时间】:2017-04-05 09:58:31
【问题描述】:
我需要在 JavaScript 中从同一站点加载另一个页面的可变内容,然后从该内容中获取数据(解析 XML)。
我已经使用 XMLHttpRequest() 和 responseText 属性在文本字符串变量中获取了页面的 HTML。
之后,我将文本字符串转换为 xml 对象(DOMParser)并尝试使用 XPath。
在 FireFox 的控制台中我看到了错误:
节点不能在它所在的文档之外的文档中使用 已创建
如何将 XMLHttpRequest() 结果转换为文档对象以使用 XPath 对其进行处理? 我应该如何使用 document.evaluate 和这个对象?有没有更简单的方法来完成我的任务?
textString=file_get_contents('my url');
var parser = new DOMParser();
xml = parser.parseFromString( textString, "text/xml" );
list = getI( "(//td[contains(text(), 'Total:')])[1]",xml);
// Error: Node cannot be used in a document other than the one in which it was created`enter code here`
// HOW USE getI function here? (document.evaluate)
function file_get_contents( url ) { // Reads entire file into a string
//
// + original by: Legaev Andrey
// % note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
var req = null;
try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {
try { req = new XMLHttpRequest(); } catch(e) {}
}
}
if (req == null) throw new Error('XMLHttpRequest not supported');
req.open("GET", url, false);
req.send();
return req.responseText;
}
function getI(xpath,elem){return document.evaluate(xpath,(!elem?document:elem),null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);}
【问题讨论】:
-
在您的
xml文档上使用evaluate方法 - 即xml.evaluate(xpath, ...
标签: javascript xpath xmlhttprequest domparser