2012-10-08 63 views
0

我有一個XML字符串是這樣的:如何使用javascript獲取嵌入在xml標籤中的值?

<?xml version="1.0"?> 
<itemsPrice> 
    <setA> 
      <Category Code="A1"> 
       <price>30</price> 
      </Category> 
      <Category Code="A2"> 
        <price>20</price> 
      </Category> 
    </setA> 
    <setB> 
      <Category Code="A3"> 
       <price>70</price> 
      </Category> 
      <Category Code="A4"> 
       <price>80</price> 
      </Category> 
    </setB> 
</itemsPrice> 

如何獲得屬性「代碼」的值在JavaScript變量或數組?我想要的是:A1,A2,A3,A4最好在一個數組中。或者,如果它可以在「每個」功能中獲得,那也是很好的。我如何在JavaScript中爲此做些什麼?

這裏是我的嘗試:

var xml=dataString; // above xml string 
xmlDoc = $.parseXML(xml); 
$xml = $(xmlDoc); 
$code = $xml.find("Category"); 
alert($code.text()); // gives me the values 30 20 70 80 
         // I want to get the values A1 A2 A3 A4 

回答

1

試試這個

var arr = []; 
$code = $xml.find("Category"); 

$.each($code , function(){ 
    arr.push($(this).attr('Code')); 
}); 

console.log(arr); // Will have the code attributes 
+0

非常感謝。它工作完美! – zolio

+0

@zolio而不是我的回答? –

1

您可以使用下面的腳本得到在陣列中的所有代碼

codeArray = [] 
$($($.parseXML(dataString)).find('Category')).each(function(){ codeArray.push($(this).attr('Code'))}) 

codeArray將["A1", "A2", "A3", "A4"]

+0

非常感謝。這段代碼工作完美,雖然對我來說有點複雜。 – zolio

+0

@zolio它其實是一樣的東西。我只是沒有將變量分配給$ .parseXML(dataString),然後爲$(xml).find('Category')分配變量。如果您將我提到的陳述替換爲變量,我會變得更容易理解。然後,它也是同樣的東西:) –

0

這應該對你有幫助

$xml.find('Category').each(function(){ 
    alert($(this).attr('Code')); 
}); 
相關問題