Home > Article > Web Front-end > How to traverse XML nodes and attributes using jQuery
This time I will show you how to use jQuery to traverse XML nodes and attributes, and what are the precautions for using jQuery to traverse XML nodes and attributes. The following is a practical case, let's take a look.
There are many ways to use jquery to traverse xml on the Internet, but after reading a lot of articles, I didn’t research on the traversal method without specifying attribute names. It seems that jquery does not have attributes. We still need to use the help of Original JSThe following is the JS code<script type="text/javascript" src="js/jquery.min.js"></script> <p id="c"></p> <script> //用于缩进, 根据节点级别 var M_DOT = 1; //递归函数, 用于遍历XML, 同时打印出来 function fn(obj){ //定义一个变量, 用于缩进 var dotString = ""; //根据缩进量, 得到缩进的长度 for(j = 1; j <= M_DOT; j++){ dotString += " "; } //jquery不支持attributes属性集, 转为原生js, 并赋给myObj变量 var myObj = obj[0].attributes; //打印缩进 $("#c").append(dotString) //打印属性集nodeName, nodeValue为原生JS, 分别表示为属性的名称, 和属性值 $(myObj).each(function(i){ $("#c").append( ($(this)[0].nodeName) + "=<u>" + ($(this)[0].nodeValue) + "</u> " ); }) //打印节点的文本 //$("#c").append( "<b>" + obj.text() + "</b><br/>"); //打印换行 $("#c").append( "<br/>"); //判断DOM有无子DOM if( obj.length > 0 ){ //如果有, 遍历之 obj.children().each(function(i){ //缩进量加一 M_DOT++; //递归遍历子DOM fn($(this)); //缩进量加一 M_DOT--; }) }else{ //如果没有子DOM, 返回false return false; } } //程序入口 $(document).ready(function() { //ajax获取xml数据, 详细用法见jquery手册 $.get('config.xml', function(d){ //len = $(d).find("*").length; //找到xml顶级结点. ('*:first'):就是查找第一个DOM. 详细说明见jquery手册 //find, children(), each, 以及后面用到的 append 等请查阅jquery手册 $(d).find('*:first').children().each(function(i){ //找到顶级结点的子结点, 并把子结点对象传给fn函数 fn($(this)); }); }); }); </script>
Attached is an XML file
Please name config.xml and place it in the same directory as the above js Download, and put them all on the site<?xml version="1.0" encoding="utf-8" ?> <roster> <student ID="s101"> <name>李华</name> <sex>男</sex> <birthday>1978.9.12</birthday> <score>92</score> <skill>Java</skill> <skill>Oracle</skill> <skill>C Sharp</skill> <skill>SQL Server</skill> </student> <student ID="s107"> <name>李寻欢</name> <sex>男</sex> <birthday>1981.4.19</birthday> <score>58</score> <skill>UML</skill> <skill>C Sharp</skill> <skill>XML</skill> <skill>SQL Server</skill> </student> </roster>I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:
How to use JS to implement buffering movement
The above is the detailed content of How to traverse XML nodes and attributes using jQuery. For more information, please follow other related articles on the PHP Chinese website!