如何使用Javascript加载XML文件内容?

时间:2021-11-15 05:09:49

I'm looking for a way to load an XML file's contents directly into a Javascript variable. Say I have the following directory structure:

我正在寻找一种方法将XML文件的内容直接加载到Javascript变量中。假设我有以下目录结构:

/index.html
/loader.js
/file.xml

In index.html, there is a <body> tag, whose contents should be replaced with the contents of the XML file. So if the XML file contains:

在index.html中,有一个标记,其内容应替换为XML文件的内容。因此,如果XML文件包含:

<element>
    <item>Item One</item>
    <item>Item Two</item>
</element>

Then after the dynamic load, the HTML would be:

然后在动态加载后,HTML将是:

...
<body>
<element>
...
</element>
</body>
...

My question is, what function can I use in loader.js to load the contents straight into a variable? I have used XmlHttpRequests and the ActiveX XMLDOM parser, but all just give me a structural data model that I then have to sort through to find my elements. I don't need to parse anything, I just want to obtain all the file contents.

我的问题是,我可以在loader.js中使用什么函数将内容直接加载到变量中?我使用过XmlHttpRequests和ActiveX XMLDOM解析器,但所有这些只是给我一个结构数据模型,然后我必须通过它来查找我的元素。我不需要解析任何东西,我只想获取所有文件内容。

Note: HTML/Javascript only, no server-side code.

注意:仅限HTML / Javascript,没有服务器端代码。

2 个解决方案

#1


4  

I think I may have figured it out. The following seems to work pretty well:

我想我可能已经弄清楚了。以下似乎工作得很好:

function loadFileToElement(filename, elementId)
{
    var xmlHTTP = new XMLHttpRequest();
    try
    {
    xmlHTTP.open("GET", filename, false);
    xmlHTTP.send(null);
    }
    catch (e) {
        window.alert("Unable to load the requested file.");
        return;
    }

    document.getElementById(elementId).innerHTML=xmlHTTP.responseText;
}

#2


2  

Maybe you can read the responseText property of XmlHttpRequests to have the plain text before the parsing?

也许你可以在解析之前读取XmlHttpRequests的responseText属性以获得纯文本?

#1


4  

I think I may have figured it out. The following seems to work pretty well:

我想我可能已经弄清楚了。以下似乎工作得很好:

function loadFileToElement(filename, elementId)
{
    var xmlHTTP = new XMLHttpRequest();
    try
    {
    xmlHTTP.open("GET", filename, false);
    xmlHTTP.send(null);
    }
    catch (e) {
        window.alert("Unable to load the requested file.");
        return;
    }

    document.getElementById(elementId).innerHTML=xmlHTTP.responseText;
}

#2


2  

Maybe you can read the responseText property of XmlHttpRequests to have the plain text before the parsing?

也许你可以在解析之前读取XmlHttpRequests的responseText属性以获得纯文本?