deserializing xml file from xstream
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();
I also try this as well:
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 structure:
<projectCar.CarImpl>
<CarModel reference="../.."></CarModel>
</projectCar.CarImpl>
If yes, I would like to hear. Thanks in advance.
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.
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
Take a look at the new method 'aliasForSystemAttribute' for a possible solution.
精彩评论