Android modifies XML files

Source: Internet
Author: User

XML needs to be used to record data in recent projects. There are few articles on the Internet.

DOM

/*** Append content to the XML document * @ param instructions * @ throws ParserConfigurationException * @ throws SAXException * @ throws IOException * @ throws TransformerException */public void append2XML (String instructions) throws ParserConfigurationException, SAXException, IOException, TransformerException {Long st = System. currentTimeMillis (); String time = DateUtils. getCurrLongTime (); DocumentBuilderFactory dbf = DocumentBui LderFactory. newInstance (); // construct DocumentBuilder db = dbf through an instance. newDocumentBuilder (); // create a Document to parse the specified Document doc = db. parse (getInputStream (); // doc = db. newDocument (); // Add an Element eModel = doc. createElement ("instructionsModel"); Element eInstructions ctions = doc. createElement ("instructions"); Element eCreatetime = doc. createElement ("createtime"); Element eLastUseTime = doc. creat EElement ("lastusetime"); // Add Text textInstructions = doc to the element. createTextNode (instructions); Text textCreatetime = doc. createTextNode (time); Text textLastUseTime = doc. createTextNode (time); eInstructions. appendChild (textInstructions); eCreatetime. appendChild (textCreatetime); elestusetime. appendChild (textLastUseTime); // obtain the eModel Of The 0th nodes of the node by Name. appendChild (eInstructions); eModel. appendChild (eCreate Time); eModel. appendChild (eLastUseTime); Node book = doc. getElementsByTagName ("instructionsList "). item (0); book. appendChild (eModel); // Add an attribute // Attr attr = doc. createAttribute ("aaa"); // create the factory object TransformerFactory tfs = TransformerFactory. newInstance (); // create the Transformer object Transformer tf = tfs. newTransformer (); // output the document to the output stream. Tf. transform (new DOMSource (doc), new StreamResult (new FileOutputStream (fu. getSDCardRoot () + File. separator + filePath + File. separator + "bb. xml "); Long hastime = System. currentTimeMillis ()-st; Log. I (TAG, "DOM mode time consumption:" + hastime );}

PULL

I checked it online for a long time. It seems that everyone agrees that PULL can only Parse XML and cannot modify XML files.

So I thought of a very troublesome modification method.

1. parse the original XML file to obtain the data set.

2. Insert new data into the collection

3. regenerate XML

The Code is as follows:

1. parse XML files

/*** Get all the instruction information in XML *** @ Param inputstream * @ return * @ throws xmlpullparserexception * @ throws ioexception */private list <instructions> parsedatesource (inputstream) throws xmlpullparserexception, ioexception {long St = system. currenttimemillis (); List <instructions> instructionslist = NULL; instructions instructionsmodel = NULL; xmlpullparser parse = xml. newpullparser (); parse. setinput (inputst Ream, "UTF-8"); int event = parse. geteventtype (); While (event! = Xmlpullparser. end_document) {Switch (event) {Case xmlpullparser. start_document: instructionslist = new arraylist <instructions> (); // initialize the command set break; Case xmlpullparser. start_tag: If (PARSE. getname (). equals ("instructionsmodel") {instructionsmodel = new instructions ctions ();} If (instructionsmodel! = NULL) {If (PARSE. getname (). equals ("Instructions") {instructionsmodel. setinstructions (PARSE. nexttext ();} else if (PARSE. getname (). equals ("createtime") {instructionsmodel. setcreatetime (PARSE. nexttext ();} else if (PARSE. getname (). equals ("lastusetime") {instructionsmodel. setlastusetime (PARSE. nexttext () ;}} break; Case xmlpullparser. end_tag: If (PARSE. getname (). equals ("instructionsmodel") {instructionslist. add (instructionsmodel); instructionsmodel = NULL;} break; default: break;} event = parse. next (); // enter the next element and trigger the corresponding event} Long hastime = system. currenttimemillis ()-ST; log. I (TAG, "Time consumed for pull parsing:" + hastime); Return instructionslist ;}

2. Insert data into the set

/*** Add the new command to the XML file * @ Param out * @ Param inputstream * @ Param instructions2 * @ throws illegalstateexception * @ throws illegalargumentexception * @ throws xmlpullparserexception * @ throws ioexception */private void append2xml (outputstream out, list <instructions> instructionslist, instructions instructions2) throws failed, illegalstateexception, ioexception, xmlpullparserexception {// avoid record command operation for (INT I = 0; I <instructionslist. size (); I ++) {instructions = instructionslist. get (I); If (instructions. getinstructions (). equals (instructions2.getinstructions () {instructionslist. remove (I); instructions2.setcreatetime (instructions. getcreatetime (); break;} instructionslist. add (0, instructions2); createinstructionxml (Out, instructionslist );}

3. How to generate a new XML file

/*** Generate an XML file based on the list * @ param out * @ param instructionsList * @ throws IllegalArgumentException * @ throws IllegalStateException * @ throws IOException */private void createInstructionXml (OutputStream out, list <Instructions> instructionsList) throws IllegalArgumentException, IllegalStateException, IOException {// TODO Auto-generated method stubXmlSerializer serializer = Xml. newSerializer (); // sets the file encoding serializer. setOutput (out, "UTF-8"); serializer. startDocument ("UTF-8", true); serializer. startTag (null, "instructionsList"); for (Instructions instructions: instructionsList) {serializer. startTag (null, "instructionsModel"); serializer. startTag (null, "instructions"); serializer. text (instructions. getInstructions (); serializer. endTag (null, "instructions"); serializer. startTag (null, "createtime"); serializer. text (instructions. getCreateTime (); serializer. endTag (null, "createtime"); serializer. startTag (null, "lastusetime"); serializer. text (instructions. getLastUseTime (); serializer. endTag (null, "lastusetime"); serializer. endTag (null, "instructionsModel");} serializer. endTag (null, "instructionsList"); serializer. endDocument (); out. flush (); out. close ();}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.