2013-05-27 72 views
0

我正在開發Java Swing應用程序,並且我想創建對象並將它們保存在XML文件中,並附帶用戶在某些文本字段中寫入的信息。從Swing應用程序中保存的XML文件

如何將這些數據保存到XML文件中以形成這些對象?

+0

看看'XMLEncoder' /'XMLDecoder'。 –

回答

0

您可以編寫自己的XML-Writer來將對象/文本寫出到XML文件中。例如使用DOM

public boolean writeCommonSettingsFromGUI() 
    { 
     DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); 
     Document doc = docBuilder.newDocument(); 

     Element rootElement = doc.createElement("NAME_OF_A_ELEMENT"); 
     doc.appendChild(rootElement); 

     Element xmlInfo = doc.createElement("NAME_OF_ANOTHER_ELEMENT"); 
     xmlInfo.setTextContent("YOUR_CONTENT_TO_SET_FOR_THIS_ELEMENT"); 
     rootElement.appendChild(xmlInfo); 

     TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
     Transformer transformer = transformerFactory.newTransformer(); 
     transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
     transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "5"); 
     transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); 
     DOMSource source = new DOMSource(doc); 

     StreamResult result = null; 

     result = new StreamResult(new File("FILE_PATH_WHERE_TO_SAVE_YOUR_XML")); 

     transformer.transform(source, result); 

     return true; 
    } 
0

使用蓖麻框架,您可以將Java類映射到XML文件,反之亦然

相關問題