Reputation: 2110
The following code works for saved XML file but won't parse HTML.
<html>
<body>
<script type="text/javascript">
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send("");
return xhttp.responseXML;
}
xml=loadXMLDoc("test.html");
path="div[@id='aa']/span[@class]//a[@href]"
// code for IE
if (window.ActiveXObject)
{
var nodes=xml.selectNodes(path);
for (i=0;i<nodes.length;i++)
{
document.write(nodes[i].childNodes[0].nodeValue);
document.write("<br />");
}
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
var nodes=xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);
var result=nodes.iterateNext();
while (result)
{
document.write(result.childNodes[0].nodeValue);
document.write("<br />");
result=nodes.iterateNext();
}
}
</script>
</body>
</html>
The test.html looks like this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="UTF-8" />
</head>
<body>
<div id="aa">
<span class="bb">
<a href="http://google.com">link 1</a>
</span>
</div>
</body>
</html>
Upvotes: 0
Views: 108
Reputation: 46548
I don't know anything about "Microsoft.XMLHTTP" but I suspect you will need to replace your HTML with XHTML if you want use an XML parser. Normal HTML doesn't obey all the rules of XML (e.g. you can have unclosed tags such as <br>
).
Upvotes: 1