<html>
<body>
<script>
//xml字符串
var xmlstring = '<?xml version=/"1.0/"?>/n'
+ '<shoppingcart date=/"14-10-2007/" total=/"123.45/">/n'
+ ' <item code=/"12345/">/n'
+ ' <name>Widget</name>/n'
+ ' <quantity>1</quantity>/n'
+ ' </item>/n'
+ ' <item code=/"54321/">/n'
+ ' <name>Another Widget</name>/n'
+' <quantity>2</quantity>/n'
+ ' </item>/n'
+ '</shoppingcart>';
//创建xml文档对象
function createXMLObject(){
var xmlobject;
try{
// convert the string to an XML object
// 用于 IE 的代码:
if (window.ActiveXObject)
{
xmlobject =new ActiveXObject("Microsoft.XMLDOM");
xmlobject.async="false";
xmlobject.loadXML(xmlstring);
}
// 用于 Mozilla, Firefox, Opera, 等浏览器的代码:
else
{
var parser=new DOMParser();
xmlobject =parser.parseFromString(xmlstring,"text/xml");
}
return xmlobject;
}catch (e){
alert('error');
}
}
function test(){
alert(xmlstring);
var xmlobject = createXMLObject();
// get the XML root item
var root = xmlobject.getElementsByTagName('shoppingcart')[0];
var date = root.getAttribute("date");
alert("shoppingcart date=" + date);
var items = root.getElementsByTagName("item");
for (var i = 0 ; i < items.length ; i++) {
// get one item after another
var item = items[i];
// now we have the item object, time to get the contents
// get the name of the item
var name = item.getElementsByTagName("name")[0].firstChild.nodeValue;
// get the quantity
var quantity = item.getElementsByTagName("quantity")[0].firstChild.nodeValue;
alert("item #" + i + ": name=" + name + " quantity=" + quantity);
}
}
</script>
跨浏览器的xml dom操作:
<input type="button" value="test" οnclick="test()">
</body>
</html>
xml dom跨浏览器操作实例
最新推荐文章于 2021-02-12 13:07:28 发布