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



我使用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文件时,我想在它中包含额外的信息——例如"Version1",作为XML注释或其他嵌入信息的方式——这可能吗?

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

注意,我知道我可以向MyObject添加一个额外的String字段或其他什么,但在这种情况下我不能这样做(即修改MyObject)。

非常感谢!

正如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);

最新更新