Deserialize an xml file from xstream

I am using Xstream to serialize a Job object. He looks normal.

but deserialization, 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) 

Has any of you helped solve this problem before?

So I did for serialization:

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

I also try this:

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

For deserialization, I did this as follows:

 XStream xstream = new XStream(); xstream.fromXML("model.xml"); 

XML structure:

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

If so, I would like to hear. Thanks in advance.

+2
source share
1 answer

fromXML does not accept the file name, try:

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

to read the contents of the file as a string.

ID '' '' '' '' '' '' '' '' '' '' '' '' '' '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 fail otherwise. See Frequently Asked Questions About XStream

Take a look at the new 'aliasForSystemAttribute' method for a possible solution.

+1
source

All Articles