The examples in this article summarize the method of JQuery parsing XML. Share it with everyone for your reference, the details are as follows:
Using JavaScript to parse XML data is a common programming task. If JavaScript can do it, JQuery can certainly do it. Let's summarize some examples of using JQuery to parse XML.
The first option:
<script type="text/javascript"> $(document).ready(function() { $.ajax({ url: 'http://localhost/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>
Second option:
<script type="text/javascript"> $.get("http://localhost/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 xml file
$.get("xmlfile.xml",function(xml){ //xml即为可以读取使用的内容,具体读取见第2点 });
2. Read xml content
If the xml read comes from an xml file, combined with the above point, the processing is as follows:
$.get("xmlfile.xml",function(xml){ $(xml).find("item").length; });
If you are reading an xml string, please note that the xml string must be surrounded by "
$("<xml><root><item></item></root></xml>").find("item").length;
Parse xml content:
Sample xml:
<?xml version="1.0" encoding="utf-8" ?> <fields> <field Name="Name1"> <fieldname>dsname</fieldname> <datatype>字符</datatype> </field> <field Name="Name2"> <fieldname>dstype</fieldname> <datatype>字符</datatype> </field> </fields>
The following is the parsing sample code:
$(xml).find("field").each(function() { var field = $(this); var fName = field.attr("Name");//读取节点属性 var dataType = field.find("datatype").text();//读取子节点的值 });
Readers who are interested in more jQuery-related content can check out the special topics of this site: "Summary of jQuery operation xml skills", "Summary of jQuery drag effects and skills", " JQuery extension skills summary", "jQuery common classic special effects summary", "jQuery animation and special effects usage summary", jquery selector usage summary " and "Summary of common jQuery plug-ins and usage"
I hope this article will be helpful to everyone in jQuery programming.