Package Com.demo.common;
Import Java.io.File;
Import Java.io.FileWriter;
Import java.io.IOException;
Import org.dom4j.Document;
Import Org.dom4j.DocumentHelper;
Import org.dom4j.Element;
Import Org.dom4j.io.XMLWriter;
/**
* @ FileName: Dom4jtest.java
* Author: Flower Non-flower mist non-fog
* @ Build Date: 2008-10-20
* @ Feature Description: Create XML document with parser in dom4j
*/
public class Dom4jtest {
public static void Main (string[] args) {
Create a document instance using the Documenthelper class. Documenthelper is the dom4j API factory class that generates XML document nodes
Document doc = Documenthelper.createdocument ();
Use the AddElement () method to create the root element catalog. AddElement () is used to add elements to an XML document
Element address = doc.addelement ("Address");
Add a processing instruction using the Addprocessinginstruction () method in the element
Address.addprocessinginstruction ("Target", "text");
Element listelement = address.addelement ("HFHWFW");
Element countryelement = listelement.addelement ("Country");
To add a property to a country element using the AddAttribute () method
Countryelement.addattribute ("Country", "the");
Element cityelement = listelement.addelement ("city");
Use the SetText () method to set the text of the city element
Cityelement.settext ("Tongcheng");
Element codeElement = listelement.addelement ("code");
Add a comment using the AddComment () method
Codeelement.addcomment ("This is post code!");
Codeelement.settext ("231430");
try {
XMLWriter XMLWriter = new XMLWriter (New FileWriter ("D:/aaaa.xml"));
Xmlwriter.write (DOC);
Xmlwriter.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}
Run the generated XML file as follows (Csdn is not familiar with the layout of the document, make it look!): <?xml version= "1.0" encoding= "UTF-8"?> -< address > <?target text?> - < HFHWFW > < Country country = " " "/> ; City > tongcheng </City > - < code > - <!--this is post code! --> 231430 </code >