บทความนี้อธิบายถึงวิธีที่ JS อ่านข้อมูลไฟล์ XML และแสดงข้อมูลในรูปแบบตาราง แบ่งปันสำหรับการอ้างอิงของคุณดังนี้:
มาดูไฟล์ XML ก่อน:
<? xml version = "1.0" standalone = "ใช่"?> <student> <stuinfo> <stuname> Zhang Qiuli </stusex> <Stusex> หญิง </stusex> <stuage> 18 </stuage> </stuinfo> <stuinfo> <stuinfo> <Stusex> 31 </stuage> </stuinfo> <stuinfo> <stuname> li Siwen </stuxame> <Stusex> ชาย </stusex> <stusex> 22 </stuage> </stuinfo> </stuinfo> <stuinfo> <moundame> Sun Honglei </stusame> <stusex> ชาย </stusex> <stuage> 32 </stuage> </stuinfo> <stuinfo> <stuage> <Stuinfo> <stuname> Jiang Lin </stuname> <Stusex> หญิง </stusex> <Stusex> หญิง </stusex> <Stusex> 23 </stuage> </stuinfo> <stuinfo> <Stuage> 22 </stuage> </stuinfo> </student>
รหัสหน้า ASPX:
< %@ page language = "C#" autoEventWireUp = "true" codebehind = "รับข้อมูลฐานข้อมูลเพื่อสร้าง xml.aspx.cs" สืบทอด = "บทที่ 1.get ฐานข้อมูลเพื่อสร้าง XML" %> <! "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns =" http://www.w3.org/1999/xhtml " loadxmldoc (dname) {if (window.xmlhttprequest) {xhttp = ใหม่ xmlhttprequest (); } else {xhttp = new ActiveXObject ("microsoft.xmlhttp"); } xhttp.open ("รับ", dname, false); xhttp.send (""); ส่งคืน xhttp.responsexml; } function readxml () {var xmldoc = loadxmldoc ("students.xml"); // รับโหนดที่ระบุ var divmsg = document.getElementById ("XMLMSG"); var msg = "<table border = '1' id = 'myTable'> <tr> <th> ชื่อ </th> <th> เพศ </th> <th> อายุ </th> <tr>"; var nodes = xmldoc.getElementsByTagname ("stuinfo"); สำหรับ (var i = 0; i <nodes.length; i ++) {msg+= "<tr>"; msg + = "<td>" + โหนด [i] .getElementsByTagname ("Stuname") [0] .FirstChild.NodeValue + "</td>"; msg + = "<td>" + โหนด [i] .getElementsByTagname ("Stusex") [0] .FirstChild.NodeValue + "</td>"; msg + = "<td>" + โหนด [i] .getElementsByTagname ("Stuage") [0] .FirstChild.NodeValue + "</td>"; msg += "</tr>"; } msg += "</table>"; divmsg.innerhtml = msg; } </script> </head> <body> <form id = "form1" runat = "เซิร์ฟเวอร์"> <div> <อินพุตประเภท = "ปุ่ม" value = "js อ่าน xml" onclick = "readxml ()"/> <br/> <div id = "xmlmsg"> </div>การดำเนินการ JS ข้างต้นส่วนใหญ่หลีกเลี่ยงการใช้เด็ก (เพราะเด็ก ๆ [0] บางครั้งปรากฏใน Firefox และรับ "/n" แทนที่จะเป็นโหนดลูกแรกที่เราต้องการคุณสามารถลองด้วยตัวเอง แต่ฉันพบสถานการณ์นี้อยู่ดี) ทำให้เข้ากันได้กับ IE และ Firefox ฉันไม่ได้ลองเบราว์เซอร์อื่น
สำหรับข้อมูลเพิ่มเติมเกี่ยวกับ JavaScript โปรดตรวจสอบหัวข้อพิเศษของเว็บไซต์นี้: "สรุปทักษะการใช้งานไฟล์ XML ของ JavaScript", "สรุปทักษะการดำเนินงาน AJAX ใน JavaScript", "สรุปทักษะการดำเนินงาน JSON ใน JavaScript" เทคนิค "," สรุปข้อผิดพลาดของ JavaScript และทักษะการดีบัก "," สรุปโครงสร้างข้อมูล JavaScript และทักษะอัลกอริทึม "," บทสรุปของอัลกอริทึมและเทคนิคการสำรวจ JavaScript Traversal "และ" สรุปการใช้งานทางคณิตศาสตร์ทางคณิตศาสตร์ JavaScript "
ฉันหวังว่าบทความนี้จะเป็นประโยชน์กับการเขียนโปรแกรม JavaScript ของทุกคน