Xpath可以对XML文件中的信息进行查找,并对XML文件树形结构进行遍历。详细语法请转:http://www.w3school.com.cn/xpath/index.asp
例子:利用在JavaScript脚本中利用Xpath对XML文件中内容进行查询,将查询结果显示到html文件中
ex1.html文件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Xpath Basis-1</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="author" content="Wayne Ng" /> <meta name="description" content="Xpath basis1" /> <meta name="revised" content="Wayne Ng, 2016/1/26" /> </head> <body onload = "startLoad()"> <p>所有英雄职业:</p> <div id = "text"></div> <script type="text/javascript" src="func1.js"></script> </body> </html>
ex1.xml文件:
<?xml version = "1.0" encoding = "UTF-8"?> <!-- Date:2016/1/26 Writer:Wayne Ng Theme:MapleStory hero briefInstruction --> <game> <warrior> <hero> <name>英雄</name> <weapons>剑、斧、钝器</weapons> <skill>终极打击</skill> </hero> <hero> <name>圣骑士</name> <weapons>剑、钝器</weapons> <skill>神圣冲击</skill> </hero> <hero> <name>黑骑士</name> <weapons>长枪、矛</weapons> <skill>黑暗穿刺</skill> </hero> </warrior> <magician> <hero> <name>主教</name> <weapons>长杖、短仗</weapons> <skill>圣光普照</skill> </hero> <hero> <name>火毒法师</name> <weapons>长杖、短仗</weapons> <skill>末日火焰</skill> </hero> <hero> <name>冰雷法师</name> <weapons>长杖、短仗</weapons> <skill>冰咆哮</skill> </hero> </magician> <archer> <hero> <name>神射手</name> <weapons>弓</weapons> <skill>暴风箭雨</skill> </hero> <hero> <name>箭神</name> <weapons>弩</weapons> <skill>终极扫射</skill> </hero> </archer> <ranger> <hero> <name>侠盗</name> <weapons>短剑、短刀</weapons> <skill>暗杀</skill> </hero> <hero> <name>隐士</name> <weapons>拳套</weapons> <skill>四连镖</skill> </hero> <hero> <name>暗影双刀</name> <weapons>短剑、短刀</weapons> <skill>终极斩</skill> </hero> </ranger> </game>
func1.js文件:
//载入待解析XML文件 function loadXMLDoc(name){ if(window.XMLHttpRequest){ var xhttp = new XMLHttpRequest(); } else{ var xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET", name , false); xhttp.send(null); return xhttp.responseXML; } function startLoad(){ var xml = loadXMLDoc("ex1.xml"); var path = "//name"; var txt = ""; //利用Xpath来查找感兴趣消息 if(window.ActiveXObject){ var nodes = xml.selectNodes(path); for(var i = 0; i < nodes.length; ++i){ txt += nodes[i].childNodes[0].nodeValue + "<br />"; } } else{ var nodes = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null); var result = nodes.iterateNext(); while(result){ txt += result.childNodes[0].nodeValue + "<br />"; result = nodes.iterateNext(); } } document.getElementById("text").innerHTML = txt; }
显示效果:
2016/1/26 By 野马菌
时间: 2024-10-12 21:45:17