查看: 476|回复: 0

[DIV/CSS] HTML使用XPATH解析XML

发表于 2018-4-6 08:00:00
test.xml:
  1. <?xml version="1.0" encoding="ISO-8859-1"?>
  2. <bookstore>
  3. <book category="COOKING">
  4. <title lang="en">Everyday Italian</title>
  5. <author>Giada De Laurentiis</author>
  6. <year>2005</year>
  7. <price>30.00</price>
  8. </book>
  9. <book category="CHILDREN">
  10. <title lang="en">Harry Potter</title>
  11. <author>J K. Rowling</author>
  12. <year>2005</year>
  13. <price>29.99</price>
  14. </book>
  15. <book category="WEB">
  16. <title lang="en">XQuery Kick Start</title>
  17. <author>James McGovern</author>
  18. <author>Per Bothner</author>
  19. <author>Kurt Cagle</author>
  20. <author>James Linn</author>
  21. <author>Vaidyanathan Nagarajan</author>
  22. <year>2003</year>
  23. <price>49.99</price>
  24. </book>
  25. <book category="WEB">
  26. <title lang="en">Learning XML</title>
  27. <author>Erik T. Ray</author>
  28. <year>2003</year>
  29. <price>39.95</price>
  30. </book>
  31. </bookstore>
复制代码
test.html:
  1. <script type="text/javascript">
  2. /*
  3. @desc 加载XHR文件
  4. @author lee [<complet@163.com>]
  5. @param file 文件路径
  6. @param async 同步或异步 true 异步 flase 同步
  7. @return xmlDoc 加载后的内容
  8. */
  9. function loadDoc(file,async=true){
  10. if(window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
  11. xmlhttp=new XMLHttpRequest();
  12. }else{ // code for IE6, IE5
  13. xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  14. }
  15. if(async === true){
  16. xmlhttp.onreadystatechange = function(){
  17. if(xmlhttp.readyState < 4){
  18. // 加载中
  19. }else if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
  20. // 成功
  21. xmlDoc=xmlhttp.responseXML;
  22. return xmlDoc
  23. }else{
  24. // 失败
  25. }
  26. }
  27. }
  28. xmlhttp.open("GET",file,async);
  29. xmlhttp.send();
  30. if(async === false){
  31. xmlDoc=xmlhttp.responseXML;
  32. return xmlDoc
  33. }
  34. }
  35. var xmlDoc = loadDoc('test.xml',false)
  36. var path="/bookstore/book/title"
  37. // code for IE
  38. if (window.ActiveXObject){
  39. var nodes=xmlDoc.selectNodes(path);
  40. for (i=0;i<nodes.length;i++){
  41. document.write(nodes[i].childNodes[0].nodeValue);
  42. document.write("<br />");
  43. }
  44. }
  45. // code for Mozilla, Firefox, Opera, etc.
  46. else if (document.implementation && document.implementation.createDocument){
  47. var nodes=xmlDoc.evaluate(path, xmlDoc, null, XPathResult.ANY_TYPE, null);
  48. var result=nodes.iterateNext();
  49. while (result){
  50. document.write(result.childNodes[0].nodeValue);
  51. document.write("<br />");
  52. result=nodes.iterateNext();
  53. }
  54. }
  55. </script>
复制代码
输出:
  1. Harry Potter
  2. Everyday Italian
  3. Learning XML
  4. XQuery Kick Start
复制代码


回复

使用道具 举报