Use of Xml-jdom

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.