使用javascript或jquery从外部xml文件加载数据 [英] Load data from an external xml file with javascript or jquery
本文介绍了使用javascript或jquery从外部xml文件加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个xml文件,如下所示:
I have an xml file that looks like this:
<?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>
我想提取数据以在控制台日志中获得这样的列表
I want to extract the data to get a list like this on the console logs
Gasp for surprise
Giggle
Say hello
我怎样才能用javascript或jquery做到这一点?这是我到目前为止的代码:
how can I do it with javascript or jquery? This is my code so far:
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"));
}
}
谢谢。
推荐答案
这是jQuery和一点香草。
This is with jQuery and a little vanilla.
<!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>
这篇关于使用javascript或jquery从外部xml文件加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文