directory

  • What is XML?
  • The XML syntax
      1. Any start tag must have an end tag;
      1. Another simplified syntax is to represent both the start and end tags in a single tag.
      1. Labels must be nested in a reasonable order, so end labels must match start labels in mirror order.
      1. All attributes must have values, and they need to be surrounded by double quotes.
      1. XML documents can have only one top-level element.
      1. XML can use custom tags.
  • Examples of the correct XML format
  • Load the XML
    • Set the content-type
  • Access to XML
  • To parse the XML
  • Disable caching – Fixes the problem of late updates
  • Failed to load or parse?

What is XML?

XML (eXtensible Markup Language) enables the Markup Language to be extended.

The XML syntax

Use the following syntax in XML

1. Any start label must have an end label.

<! XML must be closed. It is not closed.

       
<name>zhangsan
Copy the code

2. Another simplified syntax is to represent both the start and end tags in one tag.

The syntax is
. This will be translated into
in the XML parser.

Ps: It’s like a single tag in HTML, isn’t it? ^ ^)

3. Labels must be nested in a proper order. Therefore, the end labels must match the start labels in the mirror order.

<! Error code because you cannot close outer parentheses without closing all inner parentheses -->

       
<name>zhangsan<i>sample</name>haha</i>
Copy the code

4. All attributes must have values surrounded by double quotation marks.

5. XMLA document can have only one top-level element.

<! Error code because it has multiple top-level elements -->

       
<name>zhangsan</name>
<id>1</id>
<name>wangwu</name>
<id>2</id>
Copy the code

6. XML can use custom tags.

Because there are no predefined tags in XML, XML allows authors to define their own tags and their own document structure.

Examples of the correct XML format


       
<stulist>
      <student email="[email protected]">
              <name>xiaoming</name>
              <age>20</age>
      </student>
      <student email="[email protected]">
              <name>xiaogang</name>
               <age>21</age>
      </student>
</stulist>
Copy the code

Load the XML

Set the content-type

When loading XML, you don’t need to set the content-Type if it is itself an XML file; If the daemon is dynamically generated, you need to set the content-type to “text/ XML “, otherwise jQuery will use the default “text/ HTML “and parsing will fail.

Here’s how to set content-Type in several common languages.

PHP

header(“Content-Type:text/xml”);

ASP

response.ContentType=”text/xml”;

JSP

response.setContentType(“text/xml”);

Access to XML

If you have a file with the correct XML structure, you can use jQuery’s Ajax function to read it. JQuery code looks like this:

$.ajax({
  url:'ajax.xml'.type:'GET'.dataType:'xml'.timeout:1000.// Set timeout
  cache:false.// Disable caching
  error:function(xml){
    alert("Error loading XML document");
  },
  success:function(xml){
    // This is used to parse XML}})Copy the code

This allows you to read the XML, or of course use the simple $.get() and $.post() methods

$.get('ajax.xml'.function(xml){
    // This is used to parse XML
    console.log(xml);
});
Copy the code

To parse the XML

As with DOM parsing, XML documents can be parsed using find(), children() and traversal using each(), and node text and attributes can be obtained using text() and attr(). For example, parsing XML in the SUCCESS callback:

success:function(xml){
  $(xml).find("student").each(function(i){ // Find all student nodes and iterate over them
    var age = $(this).children("age"); // Get the child node
    var age_value = age.text();  // Fetch the node text
    console.log(age_value);  / / the value of id
    console.log($(this).attr("email"));  // Display student properties})}// The following is also correct
$.get("xml.xml".function(xml){
   $(xml).find("student").each(function(i,val){
     var age = $(val).children("age");
     var age_value = age.html();
     console.log(age_value);   
     console.log($(val).attr("email")); })})Copy the code

The result looks like this:

With the above code, you can successfully obtain the corresponding data, and then you can add the parsed data to the existing HTML file.

Disable caching – Fixes the problem of late updates

This problem is seen in the little Red book, and has not been encountered in specific practice, so it is recorded first.

A common problem we encounter in projects is that the data has been updated, but the old data is still passed. To avoid this, you should disable caching.

  • If you are using$.ajaxThe method just needs to be incacheProperty Settingsfalse.Pay attention tofalseIs a Boolean, not a string
  • If you are using$.postBy default, caching is disabled.
  • If you are using$.getTo avoid caching by setting the timestamp:
 $.get('ajax.xml? '+ (+new Date).function(xml){
   / /...
});
// (+new Date) = new Date().gettime ()
Copy the code

Note: Random numbers are not used because there is a high probability that random numbers will be repeated when used in large numbers, which is not the case with timestamps.

Failed to load or parse?

  • Check theContent-TypeIs it set up? (Read the passageContent-TypeSet up theSection)
  • Check theXMLIs the structure correct (see article)XMLgrammarSection)
  • withajaxThe service must be started when loading. Do not use the service in the local environment. Otherwise, an error will be reported

  • parsingxmlthejqThere is no syntax error, the prompt is, if there are many child nodes, useeachTraversal, can be used$(this)Gets the current node, can also be used$(val)Gets the current node, why$(val)Because,eachThe second argument insidevalOut of isDOMElement, so it’s going toDOMElements andJQTransformation of elements.