【问题标题】:How to get the value embedded inside the xml tag using javascript?如何使用javascript获取嵌入在xml标签中的值?
【发布时间】:2012-10-08 09:55:04
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery xml-parsing


    【解决方案1】:

    试试这个

    var arr = [];
    $code = $xml.find("Category");
    
    $.each( $code , function(){
        arr.push( $(this).attr('Code'));
    });
    
    console.log( arr);  // Will have the code attributes
    

    【讨论】:

    • @zolio 而不是我的回答?
    【解决方案2】:

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

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

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

    【讨论】:

    • 非常感谢。这段代码运行完美,但对我来说有点复杂。
    • @zolio 它实际上是一回事。我只是没有将变量分配给 $.parseXML(dataString),然后分配给 $(xml).find('Category')。如果你用变量替换我提到的语句,我会更容易理解。然后,它是同一件事:)
    【解决方案3】:

    这应该对你有帮助

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

    【讨论】:

      猜你喜欢
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多