加载并解析 XML 字符串

  1. <html>
  2. <body>
  3. <script type="text/javascript">
  4. text="<bookstore>"
  5. text=text+"<book>";
  6. text=text+"<title>Harry Potter</title>";
  7. text=text+"<author>J K. Rowling</author>";
  8. text=text+"<year>2005</year>";
  9. text=text+"</book>";
  10. text=text+"</bookstore>";
  11.  
  12. try //Internet Explorer
  13. {
  14. xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  15. xmlDoc.async="false";
  16. xmlDoc.loadXML(text);
  17. }
  18. catch(e)
  19. {
  20. try //Firefox, Mozilla, Opera, etc.
  21. {
  22. parser=new DOMParser();
  23. xmlDoc=parser.parseFromString(text,"text/xml");
  24. }
  25. catch(e) {alert(e.message)}
  26. }
  27. try
  28. {
  29. document.write("xmlDoc 已加载,可以使用。");
  30. }
  31. catch(e) {alert(e.message)}
  32. </script>
  33. </body>
  34. </html>