问题描述
我需要从 ODF 文件中获取 XML.我尝试使用 FileReader readAsText 和 readAsBinaryString 但它不起作用.
I need to get XML from a ODF file. I tried using FileReader readAsText and readAsBinaryString but its not working.
FileReader readAsText 返回 odf 文件的一些特殊字符.
FileReader readAsText returns some special characters for odf files.
使用 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);
如何使用 javascript FileReader 从 ODF 文件中获取 XML?
How can get XML from ODF file using javascript FileReader?
推荐答案
这是一个基于浏览器的示例,但这应该适用于其他 JavaScript 上下文:
Here's a browser-based example, but this should be applicable to other JavaScript contexts:
制作表格:
<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>
处理上传:(为了简洁起见,我使用 JQuery)
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>
xmldata 变量包含您的 XML,为您的魔法做好准备.
The xmldata variable contains your XML, ready for your magic.