Dom4j生成xml
< dependency>
< groupId> dom4j< / groupId>
< artifactId> dom4j< / artifactId>
< version> 1.6 .1 < / version>
< / dependency>
import org. dom4j. Document ;
import org. dom4j. DocumentHelper ;
import org. dom4j. Element ;
import org. dom4j. io. OutputFormat ;
import org. dom4j. io. XMLWriter ;
import java. io. * ;
public class CreateDom4j {
public static void main ( String [ ] args) {
createDom4j ( new File ( "F:\\dom4j.xml" ) ) ;
}
public static void createDom4j ( File file) {
try {
Document document = DocumentHelper . createDocument ( ) ;
Element root = document. addElement ( "root" ) ;
Element oneChildElement = root. addElement ( "person" ) . addAttribute ( "attr" , "root one" ) ;
oneChildElement. addElement ( "people" ) . addAttribute ( "attr" , "child one" ) . addText ( "person one child one" ) ;
oneChildElement. addElement ( "people" ) . addAttribute ( "attr" , "child two" ) . addText ( "person one child two" ) ;
Element twoChildElement = root. addElement ( "person" ) . addAttribute ( "attr" , "root two" ) ;
twoChildElement. addElement ( "people" ) . addAttribute ( "attr" , "child one" ) . addText ( "person two child one" ) ;
twoChildElement. addElement ( "people" ) . addAttribute ( "attr" , "child two" ) . addText ( "person two child two" ) ;
twoChildElement. addElement ( "people" ) . addAttribute ( "attr" , "child three" ) . addCDATA ( "person two child three" ) ;
OutputFormat format = new OutputFormat ( ) ;
format. setIndentSize ( 2 ) ;
format. setNewlines ( true ) ;
format. setTrimText ( true ) ;
format. setPadText ( true ) ;
format. setNewLineAfterDeclaration ( false ) ;
XMLWriter writer = new XMLWriter ( new FileOutputStream ( file) , format) ;
writer. write ( document) ;
System . out. println ( "dom4j CreateDom4j success!" ) ;
} catch ( UnsupportedEncodingException e) {
e. printStackTrace ( ) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
< root>
< person attr = " root one" >
< people attr = " child one" > person one child one</ people>
< people attr = " child two" > person one child two</ people>
</ person>
< person attr = " root two" >
< people attr = " child one" > person two child one</ people>
< people attr = " child two" > person two child two</ people>
< people attr = " child three" > <![CDATA[person two child three]]> </ people>
</ person>
</ root>