Java write XML (1)
赵振江
Java code to create an XML file
主要类
Documentbuilder, Documentbuilderfactory, Document, Transformerfactory, Transformer, Domsource, Streamresult
code example
CreateXml.java
PackageDemoImportJava.io.File;ImportJavax.xml.parsers.DocumentBuilder;ImportJavax.xml.parsers.DocumentBuilderFactory;ImportJavax.xml.parsers.ParserConfigurationException;ImportJavax.xml.transform.OutputKeys;ImportJavax.xml.transform.Transformer;ImportJavax.xml.transform.TransformerConfigurationException;ImportJavax.xml.transform.TransformerException;ImportJavax.xml.transform.TransformerFactory;ImportJavax.xml.transform.dom.DOMSource;ImportJavax.xml.transform.stream.StreamResult;ImportOrg.w3c.dom.Element; Public class createxml {//Create Documentbuilder Public static documentbuilder getdocumentbuilder() {Documentbuilderfactory dbf = documentbuilderfactory.newinstance (); Documentbuilder DOCB =NULL;Try{DOCB = Dbf.newdocumentbuilder (); }Catch(Parserconfigurationexception e) {//TODO auto-generated catch blockE.printstacktrace (); }returnDOCB; }Public static boolean create() {//Get Documentbuilder objectDocumentbuilder Docb=getdocumentbuilder ();//Create Document ObjectOrg.w3c.dom.Document doc=docb.newdocument ();//Set document FormatDoc.setxmlstandalone (true);//Create child nodes //Create root node FirstElement Musictype =doc.createelement ("Musictype"); Element Name=doc.createelement ("Music"); Element Pop=doc.createelement ("Pop");//Set child node text contentName.settextcontent ("Ballad");//Set properties for some child nodesName.setattribute ("id","1"); Pop.settextcontent ("Small Crowd");//Add the target child node to the target root node//Musictype.appendchild (name);//Musictype.appendchild (POP);Name.appendchild (POP); Musictype.appendchild (name);//Add the root node to the XML docment.Doc.appendchild (Musictype);//Create TransformerfactoryTransformerfactory tff=transformerfactory.newinstance ();//Create transformer object Try{Transformer tf=tff.newtransformer (); Tf.setoutputproperty (Outputkeys.indent,"Yes"); Tf.transform (NewDomsource (DOC),NewStreamresult (NewFile ("Music.xml")));return true; }Catch(Transformerconfigurationexception e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(Transformerexception e) {//TODO auto-generated catch blockE.printstacktrace (); }return false; }Public static void main(string[] args) {if(Createxml.create ()) System.out.println ("Creative success!" ");ElseSystem.out.println ("The creation failed!" "); }}
[After successful execution] It is recommended that you right-click on your project and the following files will be found in the project's root directory
music.xml
<?xml version= "1.0" encoding= "UTF-8"?><musictype><music id="1">Folk<pop>Small audience</pop></Music></musictype>
Java write XML (1)