//note.xml
<note> <date>2008-08-08</date> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting this weekend!</body> </note>
//readXml.htm
<html>
<head>
<title>E4X</title>
<script type="text/javascript"> var xmlDoc; function clickHandler() { if (window.ActiveXObject) { xmlDoc = new ActiveXObject("MSXML.DOMDocument"); if(xmlDoc == null) { window.alert("MSXML.DOMDocument isn't installed."); } else { xmlDoc.async=false; xmlDoc.load("note.xml"); document.write(xmlDoc.getElementsByTagName("body")[0].firstChild.nodeValue); } } // code for Mozilla, Firefox, etc. else if(document.implementation && document.implementation.createDocument) { xmlDoc= document.implementation.createDocument("","",null) xmlDoc.load("note.xml"); xmlDoc.onload=function()//anonymous function { document.write(xmlDoc.getElementsByTagName("body")[0].firstChild.nodeValue); } } }
</script>
</head>
<body> <span>nothing</span> <button onclick="javascript:clickHandler()"/>hello, world.
</body>
</html>
使用E4X可以很方便的读XML,如下:
function clickHandler() { xmlDoc=new XML(); xmlDoc.load("note.xml"); document.write(xmlDoc.body); //code for Internet Explorer } 而且浏览器兼容性好,可是试验一下在IE7和Firefox2.0上都不起作用。IE7报XML未定义,Firefox2.0没反应。