XML学习笔记整理
1.概念:xml 是可扩展标记语言,用于传输和存储数据、是w3c的推荐标准.
2.xml树结构
xml的元素组成了一棵文档树,由最顶端的的父元素扩散到最树最底端的子元素。
3. XML的语法
xml的声明(可选的,如果需要则放在第一行):
<?xml version="1.0" encoding="utf-8"?>
version 表示xml的版本,encoding表示编码方式
xml对大小写敏感:如<Table>和<table>是不一样的
xml的属性必须加引号
实体引用
当需要在xml文档中添加一些与标签符号冲突的符号时则需要加入实体引用
> | > |
< | < |
& | & |
' | ' |
" | "" |
注释:在 XML 中,只有字符 "<" 和 "&" 确实是非法的。大于号是合法的,但是用实体引用来代替它是一个好习惯。
4.在JavaScript中操作XML
"index.xml"的内容:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note title="index"><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>
a.获取元素的值
txt=xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
b.获取属性的值
txt=xmlDoc.getElementsByTagName("note")[0].getAttribute("title");
c.修改元素的值
x=xmlDoc.getElementsByTagName("to")[0].childNodes[0];
x.nodeValue="Easy Cooking";
d.新建属性
x=xmlDoc.getElementsByTagName("to");
x[0].setAttribute("edition","first");
e.创建元素
newel=xmlDoc.createElement("edition"); //创建edition元素
newtext=xmlDoc.createTextNode("First"); //创建文本为First的节点
newel.appendChild(newtext); //将节点追加到editon元素中
x=xmlDoc.getElementsByTagName("note"); //获取note元素
x[0].appendChild(newel); //将edition加入到第一个note元素下
f.删除元素
x=xmlDoc.getElementsByTagName("note")[0];
x.removeChild(x.childNodes[0]); //删除note元素下的第一个节点 to
js内容:
if (window.XMLHttpRequest) // IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
else // IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET","index.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
//getElementsByTagName()返回一个数组
document.getElementById("name").innerHTML=
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
document.getElementById("school").innerHTML=
xmlDoc.getElementsByTagName("school")[0].childNodes[0].nodeValue;
5.XML的命名空间
当两个不同的xml文档包含相同的元素名并且被同时使用时就会发生冲突,为了避免这种冲突,我们使用前缀来避免冲突。
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
当在 XML 中使用前缀时,一个所谓的用于前缀的命名空间必须被定义。
命名空间是在元素的开始标签的 xmlns 属性中定义的。
命名空间声明的语法如下。xmlns:前缀="URI"。
<root>
<h:table xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
</root>