Import Dom4j.jar Package
The package needs you to download.
Creating an XML file
XMLWriter writer = null;//declares an object that writes XML
OutputFormat format =
Outputformat.createprettyprint ();
Format.setencoding ("Utf-8");//Set the encoding format of the XML file
String FilePath = "f://student.xml";//Save XML file path
File File = new file (FilePath);
Document _document = Documenthelper.createdocument ();
Element _root = _document.addelement ("Student Information");//----------Root
Element student = _root.addelement ("student");
Element _id = student.addelement ("number");
_id.settext ("001");
Element _name = student.addelement ("name");
_name.settext ("Grey Machine");
Element _age = student.addelement ("Age");
_age.settext ("18");
for (int i=0;i<5;i++) {
Element _student = _root.addelement ("Record");
_student.addattribute ("Sid", "XX" +i);
_student.addattribute ("Phone", "1100" +i);
}
Try
{
writer = new XMLWriter (new FileWriter (file), format);
Writer.write (_document);
Writer.close ();
} catch (IOException e) {
E.printstacktrace ();
}
System.out.println ("End of Operation!");
To generate a result diagram:
Reading an XML file
Saxreader reader = new Saxreader ();
String FilePath = "F://student.xml";
File File = new file (FilePath);
Document document;
try {
Document = Reader.read (file);
Element root = Document.getrootelement ();//Get root node
/*element database = (Element) root.selectsinglenode ("//Student Information/student");
List List = Database.elements (); Get a collection of child elements under database element
for (Object obj:list) {
element element = (element) obj;
GetName () is the element name, GetText () is the element value
System.out.println (Element.getname () + ":" +element.gettext ());
}*/
List nodes = root.elements ("student");
for (Iterator it = Nodes.iterator (); It.hasnext ();) {
Element elm = (Element) It.next ();
For (Iterator it2=elm.elementiterator (); It2.hasnext ();) {
Element elel= (Element) It2.next ();
System.out.println (Elel.getname () + ":" +elel.gettext () + ":");
}
}
for (Iterator i = root.elementiterator ("Record"), I.hasnext ();)//Traverse all record child nodes
{
element student = (element) I.next ();
if (Student.attributevalue ("Sid"). Equals ("001"))//If the value of the record attribute SID equals 001
For (Iterator it= student.attributeiterator (); It.hasnext ();)//Get all the properties of the record node
{
Attribute Attribute = (Attribute) it.next ();
String name=attribute.getname ();//Get Property name
String Text=attribute.gettext ();//Get property value
SYSTEM.OUT.PRINTLN (name + ":" +text);
}
}
} catch (Documentexception e) {
E.printstacktrace ();
}
This document is easy to read, so it uses a control-based encoding format.
Technology sharing: Edith Academy
DOM4J parsing an XML file