如何使用javascript获取嵌入在xml标记内的值?

时间:2012-10-08 09:55:04

标签: javascript jquery xml-parsing

我有一个像这样的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>

如何获取属性的值&#34; Code&#34;在一个javascript变量或数组?我想要的是:A1,A2,A3,A4最好是阵列。或者,如果它可以在&#34;每个&#34;功能也很好。我如何使用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

3 个答案:

答案 0 :(得分:1)

您可以使用以下脚本

获取数组中的所有代码
codeArray = []
$($($.parseXML(dataString)).find('Category')).each(function(){ codeArray.push($(this).attr('Code'))})

codeArray将为["A1", "A2", "A3", "A4"]

答案 1 :(得分:1)

试试这个

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

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

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

答案 2 :(得分:0)

这应该可以帮到你

$xml.find('Category').each(function(){
   alert($(this).attr('Code'));
});
相关问题