2013-07-19 46 views
2

我使用XStream(http://x-stream.github.io/)將Java對象寫入XML並將這些XML文件作爲Java對象讀回,如此;如何使用xstream在xml文件中包含/處理元數據/註釋?

// 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 - 但我不能這樣做在這種情況下(即修改MyObject)。

非常感謝!

+0

XStream模型完全忽略了任何評論。 http://xstream.10960.n7.nabble.com/Read-Write-comments-with-Xstream-td7191.html – Makky

回答

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); 
相關問題