使用jquery将xml文件内容加载到div中

如何将xml文件内容加载到div。

这是我需要加载XML内容的HTML

XML数据

   http://sofzh.miximages.com/jquery/123.png  http://sofzh.miximages.com/jquery/11.png   http://sofzh.miximages.com/jquery/11.jpg Memory Card MSMT2G 
$6.99
http://www.test.com/Sony http://sofzh.miximages.com/jquery/i2.jpg Apple iPad
$579.95
http://www.test.com/Apple

而xml文件名是something.xml

我尝试了几种方法,但它没有用:(

我尝试了以下方法,但没有奏效。

 $('something.xml').find('name').each(function() { $("#news-container").append($(this).text() + "
"); });

试试这个:

 // Load the xml file using ajax $.ajax({ type: "GET", url: "something.xml", dataType: "xml", success: function (xml) { // Parse the xml file and get data var xmlDoc = $.parseXML(xml), $xml = $(xmlDoc); $xml.find('category[name="My t"] logo').each(function () { $("#news-container").append($(this).text() + "
"); }); } });

参考: 1。jQuery.ajax()2。parseXML()

您需要转义HTML特殊字符。 在将文本设置为div之前使用此function。

 function htmlSpecialChars(unsafe) { return unsafe .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """); } 

– 您必须先调用xml文件

  $.ajax({ url: '/something.xml', type: "GET", dataType: "xml", success: function (result) { $(result).find('name').each(function () { $("#news-container").append($(this).text() + "
"); } } });

如果您想要像我一样阅读本地文件,则可以执行以下操作:

   

这需要用户选择文件,但它确实可以获取文件的内容。 它使用HTML5 FileReader API 。

试试这个:

 var xml='http://sofzh.miximages.com/jquery/123.pnghttp://sofzh.miximages.com/jquery/11.png http://sofzh.miximages.com/jquery/11.jpgMemory Card MSMT2G
$6.99
http://www.test.com/Sony
http://sofzh.miximages.com/jquery/i2.jpgApple iPad
$579.95
http://www.test.com/Apple
'; xmlDoc = $.parseXML( xml ), $xml = $( xmlDoc ), $xml.find( "category[name='My t'] logo" ).each(function () { $("#news-container").append($(this).text() + "
"); }