Android uses DOM to generate and output XML format data
This article provides a brief explanation of how to use the DOM to generate and output XML data.
1. Generating and outputting XML data
The code and comments are as follows:
Try{Documentbuilderfactory factory = Documentbuilderfactory.newinstance (); Documentbuilder builder = Factory.newdocumentbuilder ();//Create a new Document object, not getDocument xmlDocument = Builder.newdocument ();//Create a root node and add property valuesElement root = Xmldocument.createelement ("Languages"); Root.setattribute ("foo","Bar");/** * Create first element node * / //create the corresponding element node and add the attribute value and text contentElement 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 name tag and IDE tag to LAN tagLan_1.appendchild (name_1); Lan_1.appendchild (ide_1);//Add LAN tags to the Languages tabRoot.appendchild (lan_1);/** * Create a second element node * / //create the corresponding element node and add the attribute value and text contentElement 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 name tag and IDE tag to LAN tagLan_2.appendchild (name_2); Lan_2.appendchild (ide_2);//Add LAN tags to the Languages tabRoot.appendchild (lan_2);//Add the root node into the Document objectXmldocument.appendchild (root);//output of XML data needs to be converted, using transformerTransformerfactory transformerfactory = Transformerfactory.newinstance (); Transformer Transformer = Transformerfactory.newtransformer ();//Set output PropertiesTransformer.setoutputproperty ("Encoding","UTF-8");//Create a new character output stream for output dataStringWriter StringWriter =NewStringWriter ();//Convert an XML Document object and output it to the output streamTransformer.transform (NewDomsource (XmlDocument),NewStreamresult (StringWriter)); LOG.I ("XMLDATA", stringwriter.tostring ()); }Catch(Parserconfigurationexception e) {E.printstacktrace (); }Catch(Transformerconfigurationexception e) {E.printstacktrace (); }Catch(Transformerexception e) {E.printstacktrace (); }
Android uses DOM to generate and output XML format data