Jquery parses XML strings for example sharing

  • 2020-03-30 02:27:13
  • OfStack

The first option:


<script type="text/javascript">
$(document).ready(function() {
 $.ajax({
    url: 'http://www.test.net/cgi/test.xml',
    dataType: 'xml',
    success: function(data){
     //console.log(data);
    $(data).find("channel").find("item").each(function(index, ele) {
    var titles = $(ele).find("title").text();
    var links = $(ele).find("link").text();
    console.log(titles+'-----');
    $("#noticecon").find('ol').append('<li><a href="'+links+'">'+titles+'</a></li>');
   });
  }
 });
}) 
</script>
    <div id="noticecon">
  <ol>
  </ol>
 </div>


The second option:


<script type="text/javascript">
 $.get("http://www.test.net/cgi/test.xml", function(data){
  $(data).find('channel').find('item').each(function(index, ele){
   var titles = $(ele).find('title').text();
   var links = $(ele).find('link').text();
   $("#noticecon").find('ol').append('<li><a href="'+links+'">'+titles+'</a></li>');
  })
 });
</script>
    <div id="noticecon">
  <ol>
  </ol>
 </div>


The general steps are as follows:

1. Read the XML file


$.get("xmlfile.xml",function(xml){    
 $(xml).find("item").length;    
});

2. Read the XML content

If the XML read is from an XML file, this is combined with the above point, as follows:

The same code at the page code block index 2

If you are reading an XML string, be aware that the XML string must be read by "< Xml>" And "< / xml>" Encirclement can be resolved


$("<xml><root><item></item></root></xml>").find("item").length;

Parsing XML content:

Sample XML:


<?xml version="1.0" encoding="utf-8" ?>
<fields>
  <field Name="Name1">
    <fieldname>dsname</fieldname>
    <datatype> character </datatype>
  </field>
  <field Name="Name2">
    <fieldname>dstype</fieldname>
    <datatype> character </datatype>
  </field>
</fields>

Here is the parsing sample code:


$(xml).find("field").each(function() {
 var field = $(this);
 var fName = field.attr("Name");//Read node properties
 var dataType = field.find("datatype").text();//Reads the value of the child node
});


Related articles: