[英]Load data from an external xml file with javascript or jquery
你好,
我有一個 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"));
}
}
謝謝你。
這是與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>
我找到了這個解決方案來實現這個沒有像 jQuery 這樣的依賴,但它需要一些調整所以這是我的版本:
function XMLtransformation(xslUrl, xmlUrl) {
const errorMessage = 'Unable to load the content';
const parser = new DOMParser();
// attempt to load the XSL file
const xslRequest = new XMLHttpRequest();
xslRequest.open('GET', xslUrl, false); // `false` makes the request synchronous
xslRequest.send(null);
if (xslRequest.status < 300) {
const xslStylesheet = parser.parseFromString(xslRequest.response, "application/xml");
const xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xslStylesheet);
const xmlRequest = new XMLHttpRequest();
xmlRequest.open('GET', xmlUrl, false);
xmlRequest.send(null);
if (xmlRequest.status < 300) {
const htmlDocument = xsltProcessor.transformToDocument(
parser.parseFromString(xmlRequest.response, "application/xml"),
document
);
return htmlDocument.documentElement.outerHTML;
} else {
console.error('xml load failure:');
console.error(xmlRequest.status, xmlRequest.responseText);
}
} else {
console.error('xsl load failure:');
console.error(xslRequest.status, xslRequest.responseText);
}
return errorMessage;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.