使用简单xml序列化程序(v2.6.6),java文档没有根元素异常

lokaqttq  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(315)

我使用的是简单的xml库http://simple.sourceforge.net/ 从套接字输入流反序列化对象。而在简单的java应用程序中,同样的情况也很好,在android中,我得到

MyObject obj = serializer.read(MyObject.class,socket.getInputStream())

org.simpleframework.xml.stream.nodeexception:文档没有根元素
这是为什么??

db2dz4w8

db2dz4w81#

由于我的上一篇文章被删除,我的xml再次出现在这里:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<masterclass>
    <question className="Cosmos">
        <body>What year was the first step on the Moon?</body>
        <answer valid="0">1972</answer>
        <answer valid="0">1971</answer>
        <answer valid="0">1970</answer>
        <answer valid="1">1969</answer>
    </question>
    <question className="Cosmos">
        <body>Who were the first men to walk on the Moon?</body>
        <answer valid="1">Neil Armstrong</answer>
        <answer valid="0">Michael Collins</answer>
        <answer valid="0">Eugene Cernan</answer>
        <answer valid="1">Edwin Aldrin</answer>
    </question>
    <question className="History">
        <body>When did Christening of Poland took place?</body>
        <answer valid="0">1025</answer>
        <answer valid="1">966</answer>
        <answer valid="0">866</answer>
        <answer valid="0">916</answer>
    </question>
    <question className="Math">
        <body>Stone weighs 2kg and half stone. How much stone weighs?</body>
        <answer valid="0">2.5kg</answer>
        <answer valid="0">3kg</answer>
        <answer valid="1">4kg</answer>
        <answer valid="0">5kg</answer>
    </question>
</masterclass>

下面是解组xml文件的代码

// download successed
try {
    Serializer xmlSer = new Persister();
    InputStream fis = new FileInputStream(xmlFilePath);
    BufferedReader in = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
    MasterClass mc = xmlSer.read(MasterClass.class, in);
    MasterClass mc = xmlSer.read(MasterClass.class, str);
    Toast.makeText(context.get(), ""+mc.getQuestionList().size(),
        Toast.LENGTH_LONG).show();
} catch (Exception ee) {
    Log.e("MasterClass", "xml serialize problem", ee);
}

错误在这行:

MasterClass mc = xmlSer.read(MasterClass.class, in);

更改为此项时:

String str = "", s;
while((s = in.readLine()) != null) {
    str += s;
    //Log.d("MasterClass", str);
}
MasterClass mc = xmlSer.read(MasterClass.class, str);

它开始工作了。不知道为什么。。。但根据我的研究,这可能与文件在设备上的保存方式有关:

OutputStream fos = new FileOutputStream(outputFile);
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
br.write(content);
br.flush();
br.close();

和xml文件编码-在notepad++中设置为utf-8,不带bom。
到mods:不知道如何删除,所以请删除我下面的问题,tks:)

sc4hvdpw

sc4hvdpw2#

你还没有收到数据。尝试设置日志并检查数据是否存在

相关问题