gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:18:48 28 4
gpt4 key购买 nike

我有一个像这样的 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最好在一个数组中。或者,如果它可以在“each”函数内获得,那也很好。我该如何使用 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

最佳答案

试试这个

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

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

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

关于javascript - 如何使用 javascript 获取嵌入在 xml 标签内的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12779300/

28 4 0