ImportJava.io.File;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;Importjava.io.UnsupportedEncodingException;ImportOrg.dom4j.Attribute;Importorg.dom4j.Document;Importorg.dom4j.DocumentException;ImportOrg.dom4j.DocumentHelper;Importorg.dom4j.Element;ImportOrg.dom4j.io.OutputFormat;ImportOrg.dom4j.io.SAXReader;ImportOrg.dom4j.io.XMLWriter;Importorg.junit.Test; Public classWriter3 {@Test
/**
Creating XML node Information
*/ Public voidmodify1 () {Document doc=documenthelper.createdocument (); Element Rootelem=doc.addelement ("ContactList"); Element Contactelem= Rootelem.addelement ("Contact")); Contactelem.addattribute ("id", "001"). AddAttribute ("name", "Eric"); Writes the attribute value directly on the node contactelem.addelement ("Name"). AddText ("Zhang San")); Add label name content is text contactelem.addelement ("Age"). AddText ("20"); Add tag age content belongs to text//Whether it is created, modified, or deleted after you write to the file FileOutputStream out=NewFileOutputStream ("E:/contact2.xml"); OutputFormat format=Outputformat.createprettyprint (); Format.setencoding ("Utf-8"); XMLWriter writer=NewXMLWriter (Out,format); Writer.write (DOC); Writer.close ();
The creation effect is as follows:
<?xml version= "1.0" encoding= "Utf-8"?><contactlist> <contact id= "001" Name= "Eric" > < name>jimi</name> <age>20</age> </contact> </contactList>
To modify a code snippet:
@Test Public voidModify3 ()throwsException {//modify this three lines of code Document doc=NewSaxreader (). Read (NewFile ("E:/contact2.xml")); Element name=doc.getrootelement (). Element ("contact"). Element ("name"); Name.settext ("Jimi");
FileOutputStream out=NewFileOutputStream ("E:/contact2.xml"); OutputFormat format=Outputformat.createprettyprint (); Format.setencoding ("Utf-8"); XMLWriter writer=NewXMLWriter (Out,format); Writer.write (DOC); Writer.close ();}
Java dom4j Create, modify, and delete XML file contents