質問

I'm working on this project that requires me to handle XML file on the client side. This is the scenario: The user gets to upload an XML file, the XML file's structure should be read at this point and table needs to be populated based on the information in the XML file. I don't have a problem creating the table and populating it, but what I'm wondering is can I process an XML file before uploading it to the server?

function parseXML(xml_file){
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        //xmlhttp.open("GET", "books.xml", false);
        xmlhttp.open("GET",xml_file , false);
        xmlhttp.send();
        xmlDoc = xmlhttp.responseXML; 
        alert(xmlDoc);
    }

When I use the above code after processing the file, xmlDoc will be null ...

function handleFileSelect(evt) {
    // FileList object  
        var files = evt.target.files;
    //var contents = evt.target.result;
    //alert(contents);
    parseXML(files[0]);


    // files is a FileList of File objects. List some properties.
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
        output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ', f.size, ' bytes, last modified: ', f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a', '</li>');
    }
    document.getElementById('file_list').innerHTML = '<ul>' + output.join('') + '</ul>';
}

Is there a way to do this? Of course I could do this with php ... upload the file to the server, refresh the page and use JavaScript to read the recently uploaded file. But is there a way to achieve this without uploading the XML file to the server?

DOMParse requires the file path to open:

xhttp.open("GET","books.xml",false)

Is there a way to read the file using FileReader and pass the actual file instead of the path to xhttp.open?

役に立ちましたか?

解決

This will only work in HTML5 compliant browsers:

  1. Use FileReader to get the file data

  2. Use DOMParser to parse the file as a string:

.

var parser = new DOMParser();
var doc = parser.parseFromString( fileAsString, "application/xml");
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top