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:
/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:
<element>
<item>Item One</item>
<item>Item Two</item>
</element>
Then after the dynamic load, the HTML would be:
...
<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.
Note: HTML/Javascript only, no server-side code.
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:
/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:
<element>
<item>Item One</item>
<item>Item Two</item>
</element>
Then after the dynamic load, the HTML would be:
...
<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.
Note: HTML/Javascript only, no server-side code.
Share Improve this question asked May 8, 2009 at 14:34 Craig OtisCraig Otis 32.1k33 gold badges143 silver badges239 bronze badges 1- This can be bersome to do with plain-old JavaScript, are you using any frameworks? (before someone says "use jQuery"...) – roryf Commented May 8, 2009 at 14:35
2 Answers
Reset to default 5I 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;
}
Maybe you can read the responseText property of XmlHttpRequests to have the plain text before the parsing?