问题
I am using xStream in Java to serialize a java object from a java library and deserializing it at the customer's side.
I have several problems:
If I do it like this:
XStream xstream = new XStream();
xstream.setMode(XStream.ID_REFERENCES);
xstream.autodetectAnnotations(true);
Writer writer = new FileWriter(xmlFile);
writer.write(xstream.toXML(myObject));
writer.close();
=> serializing is OK but deserializing: Exception in thread "main" com.thoughtworks.xstream.io.StreamException: : only whitespace content allowed before start tag and not . (position: START_DOCUMENT seen .... @1:1)
if I do it like this:
XStream xstream = new XStream();
xstream.setMode(XStream.NO_REFERENCES);
xstream.autodetectAnnotations(true);
Writer writer = new FileWriter(xmlFile);
writer.write(xstream.toXML(myObject));
writer.close();
=> I got serialization 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)
With xml:
<Test.Platform id="1">
<TaskImpl id="1">
<model reference="2"/>
<name>process</name>
</TaskImpl>
</Test.Platform id="1">
So Any suggestion?
Thanks in advance.
回答1:
so the thing that is overlooked here is how you are reading in the file. you are using
XStream xstream = new XStream();
xstream.fromXML("model.xml");
Which is where the period(.) is coming from in the error. The method fromXML is expecting the actual XML input and not the file name. So when it parses your xml (which is "model.xml" not the actual xml) it is giving the error. The site for XStream is down right now so I can't link to the API
Use a FileReader/BufferedReader in order to get the contents of the XML back. Something like this should work
XStream instream = new XStream();
BufferedReader br = new BufferedReader(new FileReader("model.xml"));
StringBuffer buff = new StringBuffer();
String line;
while((line = br.readLine()) != null){
buff.append(line);
}
Platform p = (Platform)instream.fromXML(buff.toString());
P.S. I was able to duplicate the problem, and fix it with the above
来源:https://stackoverflow.com/questions/6175883/xstream-errors-for-serializing-deserializing