Search code examples
javaxmlxml-parsingxstream

How to include/handle metadata/comments in xml files using xstream?


I use XStream (http://x-stream.github.io/) to write Java objects to XML and read those XML files back in as Java objects, like so;

// 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);

Basically, I want to include extra info in the XML file when I write to it - e.g. 'Version1', either as xml comments or some other way of embedding info - is this possible?

So when I read the xml file in again, I'd like to be able to retrieve this extra info.

Note, I know I could add an extra String field or whatever to MyObject - but I can't do that in this case (i.e. modify MyObject).

Many thanks!


Solution

  • As Makky points out, XStream ignores any comment, so I got this to work by doing the following;

    // 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);