Dom4j API is easy to append

xiaoxiao2021-03-06  135

Godmone -

One: The XML file to be operated XML.xml

Second: To write a node mapping of XML.xml files

--MYINFO.JAVA -

Class myinfo {public string name; public string teaching; public myinfo () {}}

Three: Additional nodes

--Appendnode.java -

import java.io. *; import org.dom4j *;. import org.dom4j.io *;. class AppendNode {private String fileName; public AppendNode (String fileName) {this.fileName = fileName;} public void initFile () { try {org.dom4j.Element info = DocumentHelper.createElement ( "info"); org.dom4j.Document root = DocumentHelper.createDocument (info); org.dom4j.io.XMLWriter xmlWriter = new XMLWriter (new java.io.FileOutputStream (this.fileName)); xmlWriter.write (root);} catch (java.io.FileNotFoundException e1) {} catch (java.io.UnsupportedEncodingException e2) {} catch (java.io.IOException e3) {}} public Void appendnode (myinfo mi) {try {org.dom4j.Element myinfo = documenthelper.createElement ("MyInfo"); org.dom4j.element name = documenthelper.createElement ("name"); org.dom4j.element t elephone = DocumentHelper.createElement ( "telephone"); org.dom4j.Element address = DocumentHelper.createElement ( "address"); name.setText (mi.name); telephone.setText (mi.telephone); address.setText (mi .address); Myinfo.add (name); Myinfo.add (TELEphone); Myinfo.add (address); org.dom4j.io.saxreader Reader = new saxreader (); org.dom4j.document root = reader.Read New java.io.fileinputStream (this.FileName)); org.dom4j.element info = root.getrootElement (); info.add (myinfo); org.dom4j.io.xmlResult result =

New XmlResult (new java.io.fileoutputstream (this.filename)); org.dom4j.io.xmlwriter Writer = Result.GETXMLWRITER (); Writer.write (root);} catch (java.io.filenotfoundexception E4) {} Catch (org.dom4j.documentException E5) {} catch (java.io.unsupportedEncodingexception e6) {} catch (java.io.ioException e7) {}}} 4: Main execution class

--XMLEXEC.JAVA -

public class XmlExec {private AppendNode appendnode; private String filename; public XmlExec () {filename = "xml.xml"; appendnode = new AppendNode (filename); appendnode.initFile (); ----------- --------------------------------------- <1> --------- ----} public void xmlAppend () {MyInfo myinfo1 = new MyInfo (); MyInfo myinfo2 = new MyInfo (); myinfo1.name = "wangkangfan"; myinfo1.telephone = "123456789"; myinfo1.address = "xiangjiang_xizihu" ; myinfo2.name = "shenmuzi"; myinfo2.telephone = "987654321"; myinfo2.address = "diao_yu_dao"; appendnode.appendNode (myinfo1); appendnode.appendNode (myinfo2);} public static void main (String args []) {XMLEXEC XML = New XMLEXEC (); XML.Xmlappend (); ----------------------------------- --------- <2> ---------------}}

Five: Result View

Execute <1>:

Execute <2>:

Six: Finally, my favorite - small dragon girl -

Haha ~

转载请注明原文地址:https://www.9cbs.com/read-127359.html

New Post(0)