问题描述
我正在使用Xstream序列化Job对象。看起来不错。
I am using Xstream to serializing a Job object. It looks working fine.
但是反序列化,我有一个问题:
but deserializing, I have a problem:
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)
你们中的一个人以前遇到过这个问题吗?
Did one of you get this problem before?
这是我进行序列化的方式:
This is the way, I did for serializing:
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);
对于反序列化,我是这样做的:
For deserializing, I did it like this:
XStream xstream = new XStream();
xstream.fromXML("model.xml");
XML结构:
<projectCar.CarImpl>
<CarModel reference="../.."></CarModel>
</projectCar.CarImpl>
如果是,我想听听。
推荐答案
fromXML没有文件名,请尝试:
fromXML does not take a filename, try:
File xmlFile = new File("model.xml");
xstream.fromXML(new FileInputStream(xmlFile));
以字符串形式读取文件内容。
to read the file contents as a String.
在XStream中,字段名 id和引用也恰好是系统属性。使用以下代码:
Also the fieldnames 'id' and 'reference' happen to be 'system attributes' in XStream. Using the following code:
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);
解组将失败,否则将成功。请参见
unmarshalling fails if the fields are called 'id' and 'reference', but succeeds otherwise. See XStream FAQ
查看新方法'aliasForSystemAttribute'寻求可能的解决方案。
Take a look at the new method 'aliasForSystemAttribute' for a possible solution.
这篇关于从xstream反序列化xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!