用jQuery读取xml

时间:2012-11-15 15:53:45

标签: jquery xml ajax dom

如果更容易,我想用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”这个词”。 <Tag />给了我一个“长度”,表示我需要选择的以下单词的长度。

我该怎么做?

现在我用:

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

1 个答案:

答案 0 :(得分: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/