This article mainly shares with you js parsing xml examples, hoping to help everyone.
Complete directory
xml code
<?xml version="1.0" encoding="gb2312"?> <CityList> <City Name="北京"> <Description>京有着三千余年的建城史和八百五十余年的建都史...</Description> </City> <City Name="上海"> <Description>上海,中国大陆第一大城市;四个中央直辖市之一</Description> </City> <City Name="广州"> <Description>广州,简称穗,别称羊城、穗城、穗垣、仙城、花城;解放前旧称省城。</Description> </City> <City Name="成都"> <Description>位于四川省中部,是中西部地区重要的中心城市。西南地区科技中心、商贸中心、金融中心和交通通信枢纽。</Description> </City> <City Name="沈阳"> <Description>沈阳,辽宁省省会,中国15个副省级城市之一,中国七大区域中心城市之一</Description> </City> </CityList>
html code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>js解析xml字符串</title> </head> <body> <script type="text/javascript" src="jquery-1.8.2.js"> </script> <script type="text/javascript"> /** * 解析xml的方法 * @param {Object} xmlFile */ var loadXML = function (xmlFile) { var xmlDoc; if (window.ActiveXObject) { xmlDoc = new ActiveXObject('Microsoft.XMLDOM');//IE浏览器 xmlDoc.async = false; xmlDoc.load(xmlFile); } else if (isFirefox=navigator.userAgent.indexOf("Firefox")>0) { //火狐浏览器 //else if (document.implementation && document.implementation.createDocument) {//这里主要是对谷歌浏览器进行处理 xmlDoc = document.implementation.createDocument('', '', null); xmlDoc.load(xmlFile); } else{ //谷歌浏览器 var xmlhttp = new window.XMLHttpRequest(); xmlhttp.open("GET",xmlFile,false); xmlhttp.send(null); if(xmlhttp.readyState == 4){ xmlDoc = xmlhttp.responseXML.documentElement; } } return xmlDoc; } $(function(){ //绑定下拉列表事件 $("#sel").change(function( ){ $("#area").val($(this).val()) }) //调用读取xml文件的方法,返回xml对象 var xml = loadXML("city.xml") //提取City数据 var countrys = xml.getElementsByTagName('City'); //循环为select下拉列表赋值 for(var i = 0; i < countrys.length; i++) { $("<option></option>").val(countrys[i].textContent).text(countrys[i].getAttribute("Name")).appendTo( $("#sel") ); }; }) </script> </body> <p></p> <body> <select id="sel"></select> <textarea id="area" cols="30" rows="10"></textarea> </body> </html>
Running effect:
js reads the content in xml, loads the city into the drop-down list, and then changes the city, the city description is displayed in the text box;
As followsCreate parsing xml object
##
<html> <body> <script type="text/javascript"> try //Internet Explorer { xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); } catch(e) { try //Firefox, Mozilla, Opera, etc. { xmlDoc=document.implementation.createDocument("","",null); } catch(e) {alert(e.message)} } try { xmlDoc.async=false; xmlDoc.load("/example/xdom/books.xml"); document.write("xmlDoc is loaded, ready for use"); } catch(e) {alert(e.message)} </script> </body> </html>
Questions about how to parse XML in PHP
The above is the detailed content of js parsing xml example sharing. For more information, please follow other related articles on the PHP Chinese website!