First, import the Jdom jar package
Write XML
public class WriteXML {
public static void Main (string[] args) throws FileNotFoundException, IOException {
Element addresslist=new Element ("AddressList");
Element linkman=new Element ("Linkman");
Element name=new Element ("name");
Element email=new Element ("email");
Attribute id = new Attribute ("id", "lxh");
Defining Document Objects
Document Doc=new document (AddressList);
Name.settext ("Xiao Li");
Set property to Element
Name.setattribute (ID);
Email.settext ("[email protected]");
Set relationship
Linkman.addcontent (name);
Linkman.addcontent (email);
Addresslist.addcontent (Linkman);
Xmloutputter out=new Xmloutputter ();
Set encoding
Out.setformat (Out.getformat (). setencoding ("GBK"));
File File=new file ("D:" +file.separator+ "Address.xml");
Out.output (doc,new fileoutputstream (file));
}
}
Read XML
public class ReadXML {
public static void Main (string[] args) throws Jdomexception, IOException {
Saxbuilder builder = new Saxbuilder ();
File File=new file ("D:" +file.separator+ "Address.xml");
Document Read_doc = builder.build (file);
Element root = Read_doc.getrootelement ();//Get Root
List List = Root.getchildren ("Linkman");//Get all the Linkman
for (int x=0;x<list.size (); x + +) {
Element e = (Element) list.get (x);
String name = E.getchildtext ("name");//Gets the contents of the name child node
String id = e.getchild ("name"). getattribute ("id"). getValue ();
String email = e.getchildtext ("email");
System.out.println ("--------------contact-------------");
System.out.println ("Name:" + name + ", Number:" + ID);
System.out.println ("email:" + email);
System.out.println ("-----------------------------------");
System.out.println ();
}
}
}
Use of Xml-jdom