2012-11-15 209 views
2

我想閱讀這個XML與jQuery或其他更容易。閱讀與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,當然我想要找回這個詞「」和單詞「」。 <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

請告訴我問題嗎? – ManseUK

+1

您錯過了提問的部分 –

+0

我想檢索單詞「books」和單詞「book」。我怎樣才能做到這一點? – enguerran

回答

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/

+0

這是一個偉大的和乾淨的代碼!我將像現在一樣使用jQuery方式,標籤是表達式(很多詞),但是,謝謝,它太棒了! – enguerran