XML Parsing with jQuery 【转】

Posted in:

XML is an important part of AJAX. Heck, it's right in the name, "Asynchronous JavaScript and XML", so knowing how to parse XML is equally important. This tutorial will demonstrate how to parse XML using jQuery that should cover almost all cases you'd typically run into.

Using jQuery to parse XML is vaguely reminiscent of LINQ in the recent .NET frameworks. That's a good thing, since LINQ made parsing XML in .NET vastly easier than previous techniques. With jQuery, when you receive XML from a callback, you're not actually getting raw text, you're actually getting a DOM (document object model) that jQuery can traverse very quickly and efficiently to give you the data you need.

Let's start by looking at the example XML document we'll be parsing today. I made a file that contains most things you'd see in a typical XML document - attributes, nested tags, and collections.

<?xml  version= "1.0"  encoding= "utf-8"  ?>
<RecentTutorials>
   <Tutorial  author= "The Reddest" >
     <Title>Silverlight and the Netflix API </Title>
     <Categories>
       <Category>Tutorials </Category>
       <Category>Silverlight 2.0 </Category>
       <Category>Silverlight </Category>
       <Category>C# </Category>
       <Category>XAML </Category>
     </Categories>
     <Date>1/13/2009 </Date>
   </Tutorial>
   <Tutorial  author= "The Hairiest" >
     <Title>Cake PHP 4 - Saving and Validating Data </Title>
     <Categories>
       <Category>Tutorials </Category>
       <Category>CakePHP </Category>
       <Category>PHP </Category>
     </Categories>
     <Date>1/12/2009 </Date>
   </Tutorial>
   <Tutorial  author= "The Tallest" >
     <Title>Silverlight 2 - Using initParams </Title>
     <Categories>
       <Category>Tutorials </Category>
       <Category>Silverlight 2.0 </Category>
       <Category>Silverlight </Category>
       <Category>C# </Category>
       <Category>HTML </Category>
     </Categories>
     <Date>1/6/2009 </Date>
</Tutorial>
   <Tutorial  author= "The Fattest" >
     <Title>Controlling iTunes with AutoHotkey </Title>
     <Categories>
       <Category>Tutorials </Category>
       <Category>AutoHotkey </Category>
     </Categories>
     <Date>12/12/2008 </Date>
   </Tutorial>
</RecentTutorials>

 

The first thing you're going to have to do is write some jQuery to request the XML document. This is a very simple AJAX request for the file.

$(document).ready( function()
{
  $.ajax({
    type:  "GET",
    url:  "jquery_xml.xml",
    dataType:  "xml",
    success: parseXml
  });
});

 

Now that that's out of the way, we can start parsing the XML. As you can see, when the request succeeds, the function parseXML is called. That's where I'm going to put my code. Let's start by finding the author of each tutorial, which are stored as attributes on the Tutorial tag.

function parseXml(xml)
{
   //find every Tutorial and print the author
  $(xml).find( "Tutorial").each( function()
  {
    $( "#output").append($( this).attr( "author") +  "<br />");
  });

   // Output:
   // The Reddest
   // The Hairiest
   // The Tallest
   // The Fattest
}

 

The quickest way to parse an XML document is to make use of jQuery's powerful selector system, so the first thing I do is callfind to get a collection of every Tutorial element. Then I call each, which executes the supplied function on every element. Inside the function body, this now points to a Tutorial element. To get an attribute's value, I simply call attr and pass it the name of what attribute I want. In this example, I have a simple HTML span object with an id of "output". I call append on this element to populate it with data. You would probably do something a little more exciting, but I just wanted a simple way to display the results.

See how easy that is? Let's now look at a slightly more complicated one. Here I want to print the publish date of each tutorial followed by the title.

//print the date followed by the title of each tutorial
$(xml).find( "Tutorial").each( function()
{
  $( "#output").append($( this).find( "Date").text());
  $( "#output").append( ": " + $( this).find( "Title").text() +  "<br />");
});

// Output:
// 1/13/2009: Silverlight and the Netflix API
// 1/12/2009: Cake PHP 4 - Saving and Validating Data
// 1/6/2009: Silverlight 2 - Using initParams
// 12/12/2008: Controlling iTunes with AutoHotkey

 

This is very similar to the previous example, except now the values are stored inside element text instead of attributes. Again, I want to go through every Tutorial tag, so I first use find and each. Once I'm inside a Tutorial, I need to find the Date, so I usefind again. To get the text inside an XML element, simply call text. I repeat the same process again for the Title, and that's it.

We've now parsed every piece of information except the categories that each tutorial belongs to. Here's the code to do that.

//print each tutorial title followed by their categories
$(xml).find( "Tutorial").each( function()
{
  $( "#output").append($( this).find( "Title").text() +  "<br />");

  $( this).find( "Category").each( function()
  {
    $( "#output").append($( this).text() +  "<br />");
  });

  $( "#output").append( "<br />");
});

// Output:
// Silverlight and the Netflix API
// Tutorials
// Silverlight 2.0
// Silverlight
// C#
// XAML

// Cake PHP 4 - Saving and Validating Data
// Tutorials
// CakePHP
// PHP

// Silverlight 2 - Using initParams
// Tutorials
// Silverlight 2.0
// Silverlight
// C#
// HTML

// Controlling iTunes with AutoHotkey
// Tutorials
// AutoHotkey

 

Once again, I get every Tutorial by using find and each. I then get the Title in the same was as the previous example. Since a tutorial can belong to several categories, I call find and each to iterate over each Category element inside a tutorial. Once I'm inside a Category element, I simple print out its contents using the text function.

Being able to parse elements, attributes, and collections should cover almost every form of XML you'd ever see, and making use of jQuery selectors to get the job done makes parsing XML in JavaScript a breeze. That does it for this tutorial. Hopefully we all learned something about jQuery and XML.

 

from:http://www.switchonthecode.com/tutorials/xml-parsing-with-jquery

欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 330987132 | Go:217696290 | Python:336880185 | 做人要厚道,转载请注明出处!http://www.cnblogs.com/sunshine-anycall/archive/2009/12/29/1635204.html
XML parsing error是指在解析XML文件时发生了错误。根据引用\[1\]和引用\[3\]的描述,这种错误可能是由于XML文件中存在语法错误或标签不匹配导致的。 在引用\[1\]中,报错信息指出了错误发生在XML文件的第1行第0列,可能是由于语法错误导致的。在引用\[2\]中,检查生成XML文件的代码并没有发现问题,但在XML文件的第10行第17列发现了非法字符“=”,这可能是导致错误的原因之一。 在引用\[3\]中,报错信息指出了标签不匹配的错误,发生在XML文件的第58行第6列。这可能是由于XML文件中的标签没有正确闭合导致的。 要解决XML parsing error,需要仔细检查XML文件的语法和标签是否正确。确保XML文件是符合XML规范的,所有的标签都正确闭合,并且没有非法字符。如果有需要,可以参考XML的规范和相关文档进行修正。 #### 引用[.reference_title] - *1* [XML parsing error: syntax error: line 1, column 0](https://blog.youkuaiyun.com/weixin_48687392/article/details/124517623)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [读取xml文件失败 Error parsing XML: not well-formed (invalid token)](https://blog.youkuaiyun.com/rrrye/article/details/104083363)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [XML parsing error: mismatched tag: line 58,column 6 xacro报错](https://blog.youkuaiyun.com/codesirL/article/details/130951398)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值