0

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

3 回答 3

1

您可以使用以下脚本获取数组中的所有代码

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

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

于 2012-10-08T10:08:52.520 回答
1

试试这个

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

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

console.log( arr);  // Will have the code attributes
于 2012-10-08T10:20:02.177 回答
0

这应该可以帮助你

$xml.find('Category').each(function(){
   alert($(this).attr('Code'));
});
于 2012-10-08T10:22:35.800 回答