How to read XML file using FileReader javascript?

社会主义新天地 提交于 2019-11-28 09:12:12

问题


I need to get XML from a ODF file. I tried using FileReader readAsText and readAsBinaryString but its not working.

FileReader readAsText returns some special characters for odf files.

with readAsBinaryString

var reader = new FileReader()

reader.onloadend=function(e){

    var data = e.target.result;
    //data is not in xml format
    var xml = str2xml(data);
    //getting error
    /*
     using DOM parser for xml parsing
    */
}

reader.readAsBinaryString(file);

How can get XML from ODF file using javascript FileReader?


回答1:


Here's a browser-based example, but this should be applicable to other JavaScript contexts:

Make a Form:

<div id="upload">
    <h2>Gimme Yo ODF Cornbread</h2>
    <form enctype="multipart/form-data" method="post">
        <input type="file" name="odfxml" id="odfxml" />
    </form>
</div>

Handle the Upload: (I'm using JQuery for brevity/simplicity)

<script>
    $("#odfxml").change(function(){
        var file = document.getElementById("odfxml").files[0];
                    //You could insert a check here to ensure proper file type
        var reader = new FileReader();
        reader.readAsText(file);
        reader.onloadend = function(){
            var xmlData = $(reader.result);
        };
    });
</script>

The xmldata variable contains your XML, ready for your magic.




回答2:


Using the response like text:

var xml = data.replace(/[\s\S]+<\?xml/, '<?xml');
xml = xml.replace(/office:document\-meta>[\s\S]+/, 'office:document-meta>');

:)

If you need to load the xml like jquery object:

xml = $(xml);

then you can use jquery selector's on



来源:https://stackoverflow.com/questions/20853219/how-to-read-xml-file-using-filereader-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!