How to construct an XML format file with dom4j

Source: Internet
Author: User
//first download and add Dom4j.jar package (Download yourself) import java.io.File; import
Java.io.FileWriter;

Import Java.io.PrintWriter;

Import Javax.swing.JOptionPane;
Import org.dom4j.Document;
Import Org.dom4j.DocumentHelper;

Import org.dom4j.Element; /** * @author WSJ * * * public class Test1 {public static void main (string[] args) throws Exception {Document DOM=DOCU Menthelper.createdocument ()//create XML file Element root=dom.addelement ("Xval");//Add root element, Xval root.addattribute ("X", "
  The value of the X string ");
  Root.settext ("Middle value of xval label");
  String Xml=dom.asxml ();
  SYSTEM.OUT.PRINTLN (XML);
  File F=new file ("D:/xml.xml");
  PrintWriter pw=new PrintWriter (f);
  Pw.write (XML);
 Pw.close (); } OR: 
/**
  * Make XML file
  * @throws Exception
 /public static void Makexml () throws exception{
  //Get Document Object
  Document document =documenthelper.createdocument ();
  Add root node
  Element root=document.addelement ("hibernate-mapping");
  Adds a node class with the attribute name name and table assigned
  Element classelement=root.addelement ("class")
  . AddAttribute ("name", " Com.aptech.User ").
  AddAttribute ("table", "T_user"); text
  //Add Property child nodes in//addtext node, add attribute Name value to "username"
  Classelement.addelement ("Property"). AddAttribute ("name", "username");
  Format output file
  OutputFormat format=outputformat.createprettyprint ();
  Declare the file
  XMLWriter writer=new XMLWriter (New FileWriter ("User2.xml"), format);
  Write out document
  writer.write (documents);
  Close file stream
  writer.close ();
  
 }

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.