3

我使用 XStream ( http://x-stream.github.io/ ) 将 Java 对象写入 XML 并将这些 XML 文件作为 Java 对象读回,就像这样;

// Writing a Java object to xml
File xmlFile = new File("/", "myObject.xml");
FileOutputStream out = new FileOutputStream(xmlFile);
MyObject myObject = new MyObject();
xstream.toXML(myObject, out);

// Reading the Java object in again
FileInputStream xmlFile = ...
XStream xStream = new XStream();
MyObject myObject = xStream.fromXML(xmlFile);

基本上,当我写入 XML 文件时,我想在 XML 文件中包含额外的信息 - 例如,“Version1”,作为 xml 注释或其他嵌入信息的方式 - 这可能吗?

因此,当我再次读取 xml 文件时,我希望能够检索到这些额外信息。

注意,我知道我可以向 MyObject 添加一个额外的字符串字段或其他任何内容 - 但在这种情况下我不能这样做(即修改 MyObject)。

非常感谢!

4

1 回答 1

2

正如 Makky 指出的那样,XStream 忽略任何评论,所以我通过执行以下操作来实现它;

// Writing a comment at the top of the xml file, then writing the Java object to the xml file
File xmlFile = new File("/", "myObject.xml");
FileOutputStream out = new FileOutputStream(xmlFile);

String xmlComment = "<!-- Comment -->"
out.write(xmlComment.getBytes());
out.write("\n".getBytes());

MyObject myObject = new MyObject();
xstream.toXML(myObject, out);

// Reading the comment from the xml file, then deserilizing the object;
final FileBasedLineReader xmlFileBasedLineReader = new FileBasedLineReader(xmlFile);
final String commentInXmlFile = xmlFileBasedLineReader.nextLine();

FileInputStream xmlFile = ...
XStream xStream = new XStream();
MyObject myObject = xStream.fromXML(xmlFile);
于 2013-07-23T08:44:59.577 回答