js获取并解析xml文件代码实例
分类:实例代码
虽说现在的javascript越来越多的和json格式数据配合使用。
但是xml文件的使用也是非常的频繁,下面就分享一段代码实例,它实现了使用javascript获取并解析xml文件的功能。
一.xml文件代码:
<?xml version="1.0" encoding="ISO-8859-1" ?> <note> <to>duncan</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting!</body> </note>
二.解析代码如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <title>前端教程网</title> <script type="text/javascript"> function parseXML(){ //Internet Explorer try{ xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); } catch(e){ //Firefox, Mozilla, Opera, etc. try { xmlDoc=document.implementation.createDocument("","",null); } catch(e){ alert(e.message); return; } } xmlDoc.async=false; xmlDoc.load("note.xml"); 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; } window.onload = function () { parseXML() } </script> </head> <body> <h1><a href="http://www.nowamagic.net" target="_blank">www.nowamagic.net</a></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> </body> </html>
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue 这段代码如何理解:
(1).xmlDoc -由解析器创建的 XML 文档。
(2).getElementsByTagName("to")[0] - 第一个 <to> 元素。
(3).childNodes[0] - <to> 元素的第一个子元素(文本节点)。
(4).nodeValue - 节点的值(文本本身)。
如果xml文件为:
<?xml version="1.0" encoding="ISO-8859-1" ?> <note> <to>antzone <too>duncan1</too> </to> <too>duncan2</too> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting!</body> </note>
读取第一个<too>:xmlDoc.getElementsByTagName("to")[0].getElementsByTagName("t00")[0].childNodes[0].nodeValue。
读取第二个<too>:xmlDoc.getElementsByTagName("too")[0].childNodes[0].nodeValue。
js获取并解析xml文件代码实例,这样的场景在实际项目中还是用的比较多的,关于js获取并解析xml文件代码实例就介绍到这了。
js获取并解析xml文件代码实例属于前端实例代码,有关更多实例代码大家可以查看。