使用javascript或jquery从外部xml文件加载数据

ggazkfy8  于 2023-01-29  发布在  Java
关注(0)|答案(2)|浏览(121)

你好,
我有一个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"));
    }
}

谢谢你。

tyg4sfes

tyg4sfes1#

这是用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>
ffscu2ro

ffscu2ro2#

我发现this solution可以在不依赖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;
}

相关问题