从xstream反序列化xml文件

时间:2011-05-26 13:55:52

标签: java deserialization xstream

我正在使用Xstream来序列化Job对象。它看起来很好。

但反序列化,我有一个问题:

Exception in thread "main" com.thoughtworks.xstream.io.StreamException:  : only whitespace content allowed before start tag and not . (position: START_DOCUMENT seen .... @1:1) 
    at com.thoughtworks.xstream.io.xml.XppReader.pullNextEvent(XppReader.java:78)
    at com.thoughtworks.xstream.io.xml.AbstractPullReader.readRealEvent(AbstractPullReader.java:137)
    at com.thoughtworks.xstream.io.xml.AbstractPullReader.readEvent(AbstractPullReader.java:130)
    at com.thoughtworks.xstream.io.xml.AbstractPullReader.move(AbstractPullReader.java:109)
    at com.thoughtworks.xstream.io.xml.AbstractPullReader.moveDown(AbstractPullReader.java:94)
    at com.thoughtworks.xstream.io.xml.XppReader.<init>(XppReader.java:48)
    at com.thoughtworks.xstream.io.xml.XppDriver.createReader(XppDriver.java:44)
    at com.thoughtworks.xstream.XStream.fromXML(XStream.java:853)
    at com.thoughtworks.xstream.XStream.fromXML(XStream.java:845)

你们其中一个人之前遇到过这个问题吗?

这就是我为序列化做的方式:

XStream xstream = new XStream();                    
Writer writer = new FileWriter(new File("model.xml"));
writer.write(xstream.toXML(myModel));
writer.close();

我也尝试过这个:

XStream xstream = new XStream();                    
OutputStream out = new FileOutputStream("model.xml");
xstream.toXML(myModel, out);

对于反序列化,我是这样做的:

XStream xstream = new XStream();

xstream.fromXML("model.xml");

XML结构:

<projectCar.CarImpl> 
   <CarModel reference="../.."></CarModel>
</projectCar.CarImpl> 

如果是,我想听听。提前谢谢。

1 个答案:

答案 0 :(得分:1)

fromXML没有文件名,请尝试:

File xmlFile = new File("model.xml");
xstream.fromXML(new FileInputStream(xmlFile));

以字符串形式读取文件内容。

此外,字段名“id”和“reference”恰好是XStream中的“系统属性”。使用以下代码:

CarImpl myModel = new CarImpl();

File xmlFile = new File("model.xml");

XStream xstream = new XStream();
xstream.useAttributeFor(String.class);
xstream.useAttributeFor(Integer.class);

Writer writer = new FileWriter(xmlFile);        
writer.write(xstream.toXML(myModel));
writer.close();

CarImpl fromXML = (CarImpl) xstream.fromXML(new FileInputStream(xmlFile));
System.out.println(fromXML);
如果字段被称为“id”和“reference”,则

解组失败,否则成功。见XStream FAQ

查看新方法'aliasForSystemAttribute'以获得可能的解决方案。