如何使用xstream在xml文件中包含/处理元数据/注释?

时间:2013-07-19 09:45:15

标签: java xml xml-parsing xstream

我使用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中添加额外的String字段或其他内容 - 但在这种情况下我不能这样做(即修改MyObject)。

非常感谢!

1 个答案:

答案 0 :(得分: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);