【问题标题】:How to include/handle metadata/comments in xml files using xstream?如何使用 xstream 在 xml 文件中包含/处理元数据/注释?
【发布时间】:2013-07-18 13:20:47
【问题描述】:

我使用 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 cmets 或其他嵌入信息的方式 - 这可能吗?

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

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

非常感谢!

【问题讨论】:

标签: java xml xml-parsing xstream


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多