1
var xml2;

function onLoad() {
    document.addEventListener("deviceready", onDeviceReady, false);
}

function onDeviceReady() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}

function gotFS(fileSystem){
    fileSystem.root.getFile("ccw.xml", null, gotFile, fail);
}

function gotFileEntry(fileEntry) {
    fileEntry.file(gotFile, fail);
}

function gotFile(file) {
    readAsText(file);
}

function readAsText(file) {

    var reader = new FileReader();

    reader.readAsText(file);    

    reader.onload = function(){
    };

    xml2 = reader.result;

    writeJson();

}

function fail(evt) {
    console.log(evt.target.error.code);
}

function parseXml(xml) {

    var dom = null;

    if (window.DOMParser) {
        try {
            dom = (new DOMParser()).parseFromString(xml, "text/xml");
        }
        catch (e) { dom = null; }
    }
    else if (window.ActiveXObject) {
        try {
            dom = new ActiveXObject('Microsoft.XMLDOM');

            dom.async = false;

            if (!dom.loadXML(xml)) // parse error ..
          window.alert(dom.parseError.reason + dom.parseError.srcText);
        }
        catch (e) { dom = null; }
    }
    else
       alert("oops");

   return dom;
}

function writeJson(){

    var json;

    //    for(var i = 0 ; i < xml.length ; i++) {
    show("\n\n" + (json = xml2json(parseXml(xml2), "  ")) + "\n\n");
    //        console.log("====="+i+"/"+xml.lenght+"=====");
    //    }
}

function show(s) { 

    document.getElementById("out").innerHTML += (s+"\n").replace(/&/g, "&amp;").replace (/</g,"&lt;").replace(/>/g,"&gt;").replace(/\n/g, "<br/>") + "<hr/>";
}

此代码是 xml 到 json 解析代码。我遵循phonegap参考。但我的文件阅读器不会改变 stateReady。那总是状态 0。请帮帮我.. filereader.result 方法在 phonegap 中不起作用?我想回家。:-( .i 将永远看到这篇文章。

4

1 回答 1

0

好吧,您可能已经解决了它,但如果对其他人有用,您的回调没有正确链接,只需使用此行更改您的行

fileSystem.root.getFile("ccw.xml", null, gotFile, fail);

fileSystem.root.getFile("ccw.xml", null, gotFileEntry, fail`);

尝试一下,也有助于添加控制台日志消息,以便您更轻松地调试和了解发生的情况和顺序。

于 2013-09-14T05:33:54.117 回答