Answered by:
Loading XML file

Question
-
I am currently building a JS App where I need to store some data in XML, which then i translate to objects. I have searched for examples about loading xml files, but I have only found two kinds:
- The ones where a external (filesystem, web) is loaded
- The ones where the XML is generated from a string
So, how could I load a file from my own app folder? I would prefer this method over parsing strings 'hard-coded' in the JS code because it's way cleaner and better for a collaborative project, but will it be slower?
Thanks in advance!
Wednesday, October 16, 2013 5:50 PM
Answers
-
I was doing this recently with JSON data by reading it as a text file and then using JSON.parse. This should work with XML data as well. This works for a data.xml file stored in the data folder of the project.
NOTE: In this example, you need to add the file to your project and you should set the file's "Copy to Output Directory" property value to "Copy Always".
var data;
function loadData() {
var uri = new Windows.Foundation.Uri('ms-appx:///data/data.xml');
return Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).then(function (file) {
return Windows.Storage.FileIO.readTextAsync(file).then(function (result) {// Process result.
data = processedResult;// Do this if you want to call this function asynchronously, handling
// the result in a .then completion handler.
return WinJS.Promise.as(true);});
});
}
- Edited by Mike Jones (CSI)Microsoft employee Wednesday, October 16, 2013 6:21 PM
- Proposed as answer by Mike Jones (CSI)Microsoft employee Wednesday, October 16, 2013 6:28 PM
- Marked as answer by ArcadioGarcia Wednesday, October 16, 2013 8:14 PM
Wednesday, October 16, 2013 6:17 PM
All replies
-
I was doing this recently with JSON data by reading it as a text file and then using JSON.parse. This should work with XML data as well. This works for a data.xml file stored in the data folder of the project.
NOTE: In this example, you need to add the file to your project and you should set the file's "Copy to Output Directory" property value to "Copy Always".
var data;
function loadData() {
var uri = new Windows.Foundation.Uri('ms-appx:///data/data.xml');
return Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).then(function (file) {
return Windows.Storage.FileIO.readTextAsync(file).then(function (result) {// Process result.
data = processedResult;// Do this if you want to call this function asynchronously, handling
// the result in a .then completion handler.
return WinJS.Promise.as(true);});
});
}
- Edited by Mike Jones (CSI)Microsoft employee Wednesday, October 16, 2013 6:21 PM
- Proposed as answer by Mike Jones (CSI)Microsoft employee Wednesday, October 16, 2013 6:28 PM
- Marked as answer by ArcadioGarcia Wednesday, October 16, 2013 8:14 PM
Wednesday, October 16, 2013 6:17 PM -
Thanks, works perfectly!Wednesday, October 16, 2013 8:14 PM