使用上载的XML文件填充HTML5输入字段

1 javascript xml html5 file-upload

我构建了一个HTML5/JS Web应用程序,它根据用户提供的数据执行相当复杂的数学计算.该应用程序通过具有几个不同的输入字段来工作,其中用户手动键入信息,然后提交以进行处理.用户输入的大部分信息不会经常变化(但通常足够硬编码也不经济),我有兴趣看看是否有办法允许用户上传所有的XML文件为每个用户定制的所需数据.字段将自动填充.用户可以根据需要更改其特定的XML文件,以在获得新计算之前反映新值.顺便说一下,任何服务器端都不是一个选择.

是否可以使用HTML5/JS上传XML文件,读取文件内容并自动填充输入字段?

Ray*_*lus 7

As I mentioned in my comment, you can accomplish this task without any server-side intervention, provided the browser has proper File API and FileReader support.

Let's say you have a file input element, where your user will select one of these XML files:

<input id="fileChooser" type="file">
Run Code Online (Sandbox Code Playgroud)

Now, you can access whatever file the user selects, grab the associated text/XML, parse it, and assign the values to text input fields on your page. Your code would look something like this:

var fileChooser = document.getElementById('fileChooser');

function parseTextAsXml(text) {
    var parser = new DOMParser(),
        xmlDom = parser.parseFromString(text, "text/xml");

    //now, extract items from xmlDom and assign to appropriate text input fields
}

function waitForTextReadComplete(reader) {
    reader.onloadend = function(event) {
        var text = event.target.result;

        parseTextAsXml(text);
    }
}

function handleFileSelection() {
    var file = fileChooser.files[0],
        reader = new FileReader();

    waitForTextReadComplete(reader);
    reader.readAsText(file);
}

fileChooser.addEventListener('change', handleFileSelection, false);
Run Code Online (Sandbox Code Playgroud)