繁体   English   中英

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

[英]How to get the value embedded inside the xml tag using 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变量或数组中获取属性“Code”的值? 我想要的是: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

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

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

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

尝试这个

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

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

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

这应该对你有帮助

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM