내 안드로이드 응용 프로그램에서 xml 파일을 사용하여 응용 프로그램 내 일부 히스토리 정보를 저장하고 있습니다.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>
그래서이 코드를 사용
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 파일 형식 I 성공적으로 파일에 새 rocord를 추가 할 수 있습니다. 하지만 안드로이드 shoud 내 목표 버전은 API 레벨 4입니다.이 코드는 API 레벨 8 이상에서 잘 작동합니다. 8.
아래의 API에DOMSource 인, 하는 TransformerFactory 클래스는 코멘트 // -------- 전에 8 그래서 모든 일에서 안드로이드 API 레벨에서 사용할 수없는> 작품
누구나 변압기 API를 사용하지 않고 xml 파일에 쓸 수있는 방법을 알고 있습니다. 미리 감사드립니다 ... 내 경우
편집 .....
I는 정보를 저장하기 위해 XML 파일을 사용해야합니다. 그래서 sharedpreferences 나 Sqlite DB에서 데이터를 저장하지 않습니다. 감사.
요구 사항에 따르면 XMl 파일 내에 정보를 저장해야합니다. 나는 Sqlite 또는 sharedpreferences를 사용할 수 없다. 그래서 XML 파일을 저장하려고합니다 ... 안드로이드의 xml 파일을 사용하여 그렇게 할 수 있습니까? – JibW
예, 가능하지만 지나치게 복잡합니다 (발생 중). 데이터를 유지하는 기본 방법은 SQLLite 또는 SharedPrefs입니다. 행운을 빕니다. – Booger