使用jQuery从XML中提取信息

时间:2011-02-16 21:49:15

标签: jquery xml parsing

当我解析XML时,我无法获得链接标记。我尝试了几种方法。这就是我现在正在使用的:

$(document).ready(function() {  

        $('#news-feed').each(function(){
         var $container = $(this);
         $container.empty();             
            $.get('blogs.xml', function(data){
         $('entry', data).each(function() {
          var $link = $('<a></a>')
          .attr('href', $('link', this).text())
          .text ($('title', this).text());
          var $headline = $('<h5></h5>').append($link);           
          var author = $(this).find('author').text();
          var pubDate = new Date(
            $('published', this).text());
            var pubMonth = pubDate.getMonth() + 1;
            var pubDay = pubDate.getDate();
            var pubYear = pubDate.getFullYear();
            var $publication = $('<div></div>')
                .addClass('publication-date')
                .text('Posted by ' + author + ' on ' + pubMonth + '/' + pubDay +'/'
                +pubYear);

         $('<div></div>')
           .append($headline, $publication)
           .appendTo($container);

            }); 
});

    });

});




<?xml version="1.0" encoding="utf-8"?>
<feed
<entry>
        <title>Quality Aspects of Flexibility and Scalability in Distance Education Design</title>
        <link rel="alternate" type="text/html" href="http://www.personal.psu.edu/author/blogs/instructional_design_and_higher_education/2010/09/quality-aspects-of-flexibility-vs-scalability-in-distance-education-design.html" />
        <id>tag:www.personal.psu.edu,2010:/author/blogs/instructional_design_and_higher_education//16140.270413</id>

        <published>2010-09-02T13:21:31Z</published>
        <updated>2010-09-16T12:49:51Z</updated>
        <author>
            <name>author</name>

        </author>

        <category term="3204" label="distance education" scheme="http://www.sixapart.com/ns/types#tag" /><category term="59026" label="flexible design" scheme="http://www.sixapart.com/ns/types#tag" /><category term="48647" label="wcldportfoliopilot" scheme="http://www.sixapart.com/ns/types#tag" /><category term="54688" label="wcldwebsite" scheme="http://www.sixapart.com/ns/types#tag" />
        <content type="html" xml:lang="en" xml:base="http://www.personal.psu.edu/author/blogs/instructional_design_and_higher_education/">



        </content>
    </entry>
</feed>

1 个答案:

答案 0 :(得分:1)

您正在检索链接的.text(),但链接标记是自动关闭的,因此它没有文字。

使用$('link', this).attr('href')从链接标记的href属性中提取网址。