Android uses DOM to generate and output XML format data
Android uses DOM to generate and output XML format data
This document describes how to use DOM to generate and output XML data.
1. Generate and output XML data
The code and comments are as follows:
Try {DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance (); DocumentBuilder builder = factory. newDocumentBuilder (); // create a new Document object, instead of obtaining Document xmlDocument = builder. newDocument (); // create the root node and add the attribute value Element root = xmlDocument. createElement ("Ages"); root. setAttribute ("foo", "bar");/*** create the first element node * // create the corresponding element node, and add the property value and text content Element lan_1 = xmlDocument. createElement ("lan"); lan_1.setAttribute ("id", "1"); Element name_1 = xmlDocument. createElement ("name"); name_1.setTextContent ("Java"); Element ide_1 = xmlDocument. createElement ("ide"); ide_1.setTextContent ("Eclipse"); // Add the name tag and ide tag to the lan tag lan_1.appendChild (name_1); lan_1.appendChild (ide_1 ); // Add the lan label to the ages label root. appendChild (lan_1);/*** create the second Element node * // create the corresponding Element node and add the attribute value and text content Element lan_2 = xmlDocument. createElement ("lan"); lan_2.setAttribute ("id", "2"); Element name_2 = xmlDocument. createElement ("name"); name_2.setTextContent ("Swift"); Element ide_2 = xmlDocument. createElement ("ide"); ide_2.setTextContent ("XCode"); // Add the name tag and ide tag to the lan tag lan_2.appendChild (name_2); lan_2.appendChild (ide_2 ); // Add the lan label to the ages label root. appendChild (lan_2); // Add the root node to xmlDocument in the Document Object. appendChild (root); // The XML data output needs to be converted, using Transformer TransformerFactory transformerFactory = TransformerFactory. newInstance (); Transformer transformer = transformerFactory. newTransformer (); // sets the output attribute transformer. setOutputProperty ("encoding", "UTF-8"); // create a new character output stream for output data StringWriter stringWriter = new StringWriter (); // convert the XML Document Object and output it to transformer in the output stream. transform (new DOMSource (xmlDocument), new StreamResult (stringWriter); Log. I ("XMLDATA", stringWriter. toString ();} catch (ParserConfigurationException e) {e. printStackTrace ();} catch (TransformerConfigurationException e) {e. printStackTrace ();} catch (TransformerException e) {e. printStackTrace ();}