2012-10-08 65 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')); 
}); 
相关问题