Example Analysis of jQuery Method for loading and parsing XML files, jqueryxml
This document describes how jQuery loads and parses XML files. We will share this with you for your reference. The details are as follows:
1. Brief Introduction
XML (eXtensible Markup Language) can be used to expand the Markup Language. Like HTML, It is a standard general-purpose SGML Language.
2. Content-Type
In many cases, the XML file cannot be parsed normally because the Content-Type is not set properly. If Content-Type is an XML file, you do not need to set it. If it is dynamically generated by the background program, you need to set Content-Type to "text/xml ", otherwise, jQuery will use the default "text/html" method, resulting in parsing failure. The following describes how to set Content-Type in several common languages.
Header ("Content-Type: text/xml"); // PHP
Response. ContentType = "text/xml"; // ASP
Response. setContentType ("text/xm"); // JSP
3. Create an instance XML document (Student. xml)
<?xml version="1.0" encoding="utf-8" ?><stulist> <student email="peter@163.com"> <name>peter</name> <id>1</id> </student> <student email="ken@163.com"> <name>ken</name> <id>2</id> </student></stulist>
4. Get XML
$ (Document ). ready (function () {$. ajax ({url: '/xml/Student. xml', type: 'get', ype: 'xml', timeout: 1000, // set timeout cache: false, // disable cache error: function (xml) {alert ("An error occurred while loading the XML document! ") ;}, Success: GetStudentComplete // callback function after successful setting });});
Use the Ajax function of JQuery to read data.
5. interpret XML
// Call back the function GetStudentComplete (XML) {$ (xml ). find ("student "). each (function (I) {// find all student nodes and traverse var id =$ (this ). children ("id"); // obtain the subnode var id_vaule = id. text (); // get the node text var email_vaule = $ (this ). attr ("email"); // obtain the node attributes alert (id_vaule); alert (email_vaule );});}
Similar to DOM parsing, you can use functions such as find () and children () to parse XML documents and use the each () method for traversal. You can also use text () and the attr () method to obtain the node text and attributes.
PS: Here are some online tools related to xml operations for your reference:
Online XML/JSON conversion tools:
Http://tools.jb51.net/code/xmljson
Online formatting XML/online compression XML:
Http://tools.jb51.net/code/xmlformat
XMLOnline compression/formatting tools:
Http://tools.jb51.net/code/xml_format_compress
XmlCode Online formatting and beautification tools:
Http://tools.jb51.net/code/xmlcodeformat