解析XML
参考https://www.runoob.com/xml/xml-dom.html
score.xml
<?xml version="1.0" encoding="UTF-8"?>
<score>
<name>
<alias>张三</alias>
<math>89</math>
<english>90</english>
</name>
<name>
<alias>李四</alias>
<math>92</math>
<english>87</english>
</name>
<name>
<alias>王五</alias>
<math>95</math>
<english>90</english>
</name>
</score>
实现代码
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","./xml/score.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var names = xmlDoc.getElementsByTagName("name");
//将文件内容输出到浏览器上
for(var i=0;i<names.length;i++){
document.write("<div>");
document.write("姓名:");
document.write(names[i].getElementsByTagName("alias")[0].childNodes[0].nodeValue);
document.write(" 数学:")
document.write(names[i].getElementsByTagName("math")[0].childNodes[0].nodeValue);
document.write(" 英语:");
document.write(names[i].getElementsByTagName("english")[0].childNodes[0].nodeValue);
document.write("</div>");
}
</script>
</body>
</html>
效果
修改XML文件
参考链接https://www.runoob.com/xml/xml-dom-advanced.html
Book.xml
<?xml version="1.0" encoding="utf-8" ?>
<books>
<book>
<title>Java面向对象编程</title>
<author>孙卫琴</author>
</book>
<book>
<title>JSP动态网页编程技术</title>
<author>李伟民</author>
</book>
<book>
<title>精通Hibernate</title>
<author>刘洋</author>
</book>
</books>
实现代码
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","./xml/Book.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var books = xmlDoc.getElementsByTagName("book");
for(var i=0;i<books.length;i++){
// 给title结点的内容后面添加“(电子工业出版社)”
var title = books[i].getElementsByTagName("title")[0].childNodes[0];
title.nodeValue=title.nodeValue+"(电子工业出版社)";
// 给book设置属性category
books[i].setAttribute("category","value"+i);
// 给book添加新元素price
price = xmlDoc.createElement("price");
price_value = xmlDoc.createTextNode("13.99元");
price.appendChild(price_value);
books[i].appendChild(price);
}
console.log(xmlDoc.childNodes[0]);
// 移除最后一个book
xmlDoc.childNodes[0].removeChild(books[books.length-1]);
console.log(xmlDoc.childNodes[0]);
</script>
</body>
</html>
效果
读取的时候需要以服务器的形式进行,即类似http://localhost:5050/index.html的形式打开网页,不然访问xml文件的时候会出问题(单独访问网页,地址栏开头是file://…会翻车),类似跨域问题