In the previous article we talked about the dom4j read XML 4 ways, very exciting, then how to write XML? We look directly at the source code implementation .
public static void Main (string[] args) throws Exception {//Create Document documents = Documenthelper.createdocument ();//Set up Code document.setxmlencoding ("GBK");//create root node element root = Document.addelement ("students");//Create xmlns XML Namespaceroot.addnamespace ("", "http://www.abc.com/ns/test"); Root.addnamespace ("T", "http://www.abc.com/ns/test" ); Root.addnamespace ("xsi", "http://www.w3.org/2001/XMLSchema-instance");//Create Attribute Root.addattribute ("xsi: SchemaLocation "," Http://www.abc.com/ns/test student.xsd ");//create Object array student[] s = new student[5];//Create object s[0] = new Student ("001", "Za", "[email protected]", (+), true); s[1] = new Student ("002", "ZB", "[email protected]", 51 S[2] = new Student ("003", "ZC", "[email protected]", and "s[3" = new Student ("004", "ZD", "[Emai L protected] ", s[4] = new Student (" 005 "," Ze "," [email protected] ", si, +, true);//write to object for (int i = 0; i < s.length; i++) {Student Stu = s[i];//Create root node element e1 = Root.addelemeNT ("Student", "http://www.abc.com/ns/test"); Add child element E1.addelement ("id"). AddText (Stu.getid ()); E1.addelement ("name"). AddText (Stu.getname ()); E1.addelement (" Email "). AddText (Stu.getemail ()); E1.addelement (" Gender "). AddText (Stu.getgender ()? "Male": "female"), E1.addelement ("Age"). AddText ("" + Stu.getage ()) e1.addelement ("Java"). AddText ("" + Stu.getjava ());} Create output stream FileOutputStream fos = new FileOutputStream ("Student.xml");//Set encoding outputstreamwriter OSW = new OutputStreamWriter (FOS, "GBK"); OutputFormat of = new OutputFormat (); Of.setencoding ("GBK"); Of.setindent (true); O F.setindent (""); Of.setnewlines (true);//write file XMLWriter writer = new XMLWriter (OSW, of); Writer.write (document); Writer.close ();}
The above code is concise. Everyone can write their own debugging under.
This site article is for baby bus SD. Team Original, reproduced must be clearly noted: (the author's official website: Baby bus )
Reprinted from "Baby bus Superdo Team" original link: http://www.cnblogs.com/superdo/p/5140399.html
[Javaweb Basics] 031.dom4j methods for writing XML