Android data store in XML files

TerryR

New Member
In my android application I am using an xml file to store some history information within the application. Following is the code I use to enter a new record to the file.\[code\]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(); }}\[/code\]XML file format\[code\]<?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>\[/code\]So using this code I can successfully add a new rocord to the file. But My minimum target version in android shoud be API level 4. This code works well with API Level 8 and above.DOMSource, TransformerFactory classes are not available in android API levels under 8. So All the things before the comment //--------> works in APIs below 8. Does anyone know any way that I can write to the xml file without using Transformer APIs. Thanks in advance...EDITS.....In my case I have to use a xml file to store information. That's why I don't look for sharedpreferences or Sqlite DB to store data. Thanks.
 
Back
Top