私のAndroidアプリケーションでは、xmlファイルを使用してアプリケーション内に履歴情報を保存しています。
以下は、ファイルに新しいレコードを入力するために使用するコードです。
String filename = "file.xml";
File xmlFilePath = new File("/data/data/com.testproject/files/" + filename);
private void addNewRecordToFile(History history)
{
try
{
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.parse(xmlFilePath);
Element rootEle = doc.getDocumentElement();
Element historyElement = doc.createElement("History");
rootEle.appendChild(historyElement);
Element customerEle = doc.createElement("customer");
customerEle.appendChild(doc.createTextNode(history.getCustomer()));
historyElement.appendChild(customerEle);
Element productEle = doc.createElement("product");
productEle.appendChild(doc.createTextNode(history.getProduct()));
historyElement.appendChild(productEle);
//-------->
DOMSource source = new DOMSource(doc);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult result = new StreamResult(xmlFilePath);
transformer.transform(source, result);
}
catch (ParserConfigurationException e)
{
Log.v("State", "ParserConfigurationException" + e.getMessage());
}
catch (SAXException e)
{
Log.v("State", "SAXException" + e.getMessage());
}
catch (IOException e)
{
Log.v("State", "IOException" + e.getMessage());
}
catch (TransformerConfigurationException e) {
e.printStackTrace();
}
catch (TransformerFactoryConfigurationError e) {
e.printStackTrace();
}
catch (TransformerException e) {
e.printStackTrace();
}
}
XML ファイル形式
<?xml version="1.0" encoding="UTF-8"?>
<HistoryList>
<History>
<customer>Gordon Brown Ltd</customer>
<product>Imac</product>
</History>
<History>
<customer>GG Martin and Sons</customer>
<product>Sony Vaio</product>
</History>
<History>
<customer>PR Thomas Ltd</customer>
<product>Acer Laptop</product>
</History>
</HistoryList>
したがって、このコードを使用して、ファイルに新しいコードを正常に追加できます。しかし、Android の最小ターゲット バージョンは API レベル 4 である必要があります。このコードは、API レベル 8 以降でうまく機能します。
DOMSource、TransformerFactoryクラスは、8 未満の Android API レベルでは使用できません。したがって、コメント//-------->の前のすべてのものは、 8 未満の API で機能します。
Transformer APIを使用せずに xml ファイルに書き込む方法を知っている人はいますか? 前もって感謝します...
編集.....
私の場合、xml ファイルを使用して情報を保存する必要があります。そのため、データを保存するための sharedpreferences や Sqlite DB を探しません。ありがとう。