XML
- XML仅仅是纯文本,被设计用来结构化、存储以及传输信息
- 没有预定义标签,可以拥有自己的标签
- 不会替代HTML,而是HTML的补充
- 通过几行的JavaScript,就可以读取一个外部XML,然后更新HTML里的数据内容
- 未来的应用程序使用 XML 来交换数据,XHML\WSDL\WAP\WML\RSS\RDF\OWL\SMIL
XML结构
了解DDT/XML Schema/XSLT
XML具有出色的自我描述性
<?xml version="1.0" encoding="ISO-8859-1"?>
<noto>
<to>Georgo</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
- XML中空格会被保留,HTML会将连续的空格合并为一个
运用实体引用代替特殊字符
<
<
&glt;
>
&
&
'
单引号
"
引号
元素
- 元素可以拥有属性,可扩展
- 名称避免使用"- . :"
属性
- 属性通常提供不属于数据组成部分的信息,文本类型与属性无关,但是对处理这个元素的软件很重要
- 属性无法包含多重的值,无法描述树结构,不易扩展,难以阅读
<file type="gif">computer.gif</file>
XMLHttpRequest 对象
在不重新加载页面的情况下更新网页
- 创建XMLHttpRequest对象
xmlhttp = new XMLHttpRequest();
- 解析XML文档
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","books.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
XML DOM
- 定义了访问文本对象的标准方法
xmlDOc.getElementsByName("to")[0].childNodes[0].nodeValue
- HTML DOM访问所有HTML元素
- 使用DOM改变HTML元素文本
document.getElementByID("to").innerHTML=
解析XML
- 跨浏览器实例
<html>
<body>
<h1>W3School.com.cn Internal Note</h1>
<p><b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span>
<script type="text/javascript">
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","note.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
- 规定数组的下标 [0],这是因为
getElementsByTagName()
方法会返回包含所有<from>
节点的数组。
- 解析XML字符串
<html>
<body>
<h1>W3School.com.cn Internal Note</h1>
<p><b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span></p>
<script>
txt="<note>";
txt=txt+"<to>George</to>";
txt=txt+"<from>John</from>";
txt=txt+"<heading>Reminder</heading>";
txt=txt+"<body>Don't forget the meeting!</body>";
txt=txt+"</note>";
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(txt);
}
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
网友评论