使用 jQuery 读取 xml

Posted

技术标签:

【中文标题】使用 jQuery 读取 xml【英文标题】:Reading xml with jQuery 【发布时间】:2012-11-04 06:32:02 【问题描述】:

如果更容易的话,我想用 jQuery 或其他东西来阅读这个 xml。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Film SYSTEM "film_commentaries_opinion.dtd">

<Film lang="fr" title="Mixed" originalTitle="">
 <Actors>
 </Actors>
 <Comments>
  <Comment>films adapted from comic <Tag length="5" />books have had plenty
    of success, whether they're about superheroes (batman, superman, spawn), 
    or geared toward kids (casper) or the arthouse crowd (ghost world), but 
    there's never really been a comic <Tag length="4" />book like from 
    hell before. For starters, it was created by Alan Moore 
    (and Eddie Campbell), who brought the medium to a whole new level in the 
    mid '80s with a 12-part series called the watchmen.</Comment>
 </Comments>
</Film>

当然我不能更改我的富皇帝客户端给出的xml,当然我要检索的是单词“books”和单词“book ”。 &lt;Tag /&gt; 给了我一个“length”,它代表我需要选择的以下单词的长度。

我该怎么做?

现在我使用:

  $.ajax(
    type: 'GET', url: 'data/mergedXML_PangLee.xml.tag.xml', dataType: 'xml',
    success: function(xml) 
        var tags = $(xml).find("Tag");
        // other code here...
    

【问题讨论】:

你错过了提问的部分 我要检索单词“books”和单词“book”。我该怎么做? 只有评论标签里面的标签吗? 有:&lt;Comments&gt;&lt;Comment&gt;&lt;Tags&gt;1&lt;/Tags&gt;....&lt;Tags&gt;n&lt;/Tags&gt;&lt;/Comment&gt;&lt;/Comments&gt; 【参考方案1】:

jQuery 方式

success: function(xml) 

    var liveXml = $(xml),
        inTagMode = false,
        tagLength,
        tags = [];

    liveXml.find('Comment').contents().each(function()
        var node = $(this),
            value = node.text();

        if (inTagMode)
            tags.push( value.substring(0,tagLength) );
            inTagMode = false;
         else 
            if (this.nodeName.toLowerCase() === 'tag')
                inTagMode = true;
                tagLength = node.attr('length');
            
        
    );


演示地址 http://jsfiddle.net/gaby/wtykx/


正则表达式方式(假设标签为全词

success: function(xml) 
    var regex = /(?:<tag.*?\/>)(..*?\b)/gi;
    var tags = [], result;
    while(result = regex.exec(xml))
        tags.push(result[1]);
    

演示地址 http://jsfiddle.net/gaby/wtykx/1/

【讨论】:

这是一个伟大而干净的代码!我会像现在一样使用jQuery的方式,标签是表达(很多词),但是谢谢,太好了!

以上是关于使用 jQuery 读取 xml的主要内容,如果未能解决你的问题,请参考以下文章

如何用jquery/javascript读取xml文件

jQuery - 基于变量参数查找xml子项

如何使用 PHP 缩小 XML?

JQuery中的html(),text(),val()区别

使用 jQuery Mobile 进行 XML 解析

jQuery .append() 在 IE、Safari 和 Chrome 中不起作用