您好,
我有一个xml文件,如下所示:
<?xml version="1.0"?>
<sendSound enable="true" autoPlay="true">
<item name="Gasp for surprise" src="flashsound/gasp.mp3"></item>
<item name="Giggle" src="flashsound/hehe.mp3"></item>
<item name="Say hello" src="flashsound/hello.mp3"></item>
</sendSound>
我想提取数据以在控制台日志中获得这样的列表
Gasp for surprise
Giggle
Say hello
我怎么能用javascript或jquery做到这一点?到目前为止,这是我的代码:
var users = xml.getElementsByTagName("sendSound");
for(var i = 0; i < users.length; i++) {
var user = users[i];
var names = user.getElementsByTagName("item");
for(var j = 0; j < names.length; j++) {
console.log(names[j].getAttribute("name"));
}
}
谢谢。
答案 0 :(得分:2)
这是jQuery和一点香草。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.parseXML demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
$.get( "./file.xml", function( data ) {
var xml = new XMLSerializer().serializeToString(data);
var xmlDoc = $.parseXML( xml );
var xml = $( xmlDoc );
var users = xml.find( "sendSound" );
for(var i = 0; i < users.length; i++) {
var user = users[i];
var names = user.getElementsByTagName("item");
for(var j = 0; j < names.length; j++) {
console.log(names[j].getAttribute("name"));
}
}
});
</body>
</html>