当前位置: 首页 > 面试题库 >

从xstream反序列化xml文件

戚京
2023-03-14
问题内容

我正在使用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>

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


问题答案:

fromXML没有文件名,请尝试:

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

以String形式读取html" target="_blank">文件内容。

在XStream中,字段名“ id”和“引用”也恰好是“系统属性”。使用以下代码:

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常见问题解答

看一下新方法’aliasForSystemAttribute’的可能解决方案。



 类似资料:
  • 我在尝试“反序列化”对象时遇到以下错误: 我需要能够使用这个XStream库序列化/反序列化对象,甚至是那些没有参数构造函数的对象。

  • 为了完整起见,我在下面添加了我的代码。 而且

  • 我正在使用xstream并尝试将列表序列化为XML。我需要一个输出结构 序列化的对象类似于 我的问题与作为对象集合的XStream-Root类似,但我希望在不使用包装对象的情况下这样做。

  • 我目前正在使用XStream来解析XML文件,但无法使它执行我需要它执行的操作。如果有必要,我会换另一个图书馆,任何可以解决这个问题的! 我正试图将其解析为如下所示的模型: 标题写得很好,但我很难解析作者。不幸的是,以这样一种“更合理”的格式获取XML提要并不是一种选择: 我可以做什么来将“author1”、“author2”等解析成一个列表吗?

  • 我加载xml文件如下 使2类 我加载xml文件(temp.xml),然后序列化类2位置和头然后StringReader,它从文件中读取字符串,然后类序列化成为反序列化 但我看到error error msg在XML文档中有一个错误(1,1)。哪里?:at系统。Xml。序列化。XmlSerializer。在系统上反序列化(XmlReader XmlReader、String encodingStyl