Dom4j xml file operations (full)

Source: Internet
Author: User
Tags ftp connection
Many of us use xml files in projects, whether it is parameter configuration or data interaction with other systems. Many of us use xml files in projects, whether it is parameter configuration or data interaction with other systems.
Today, let's talk about using dom4j in Java to operate XML files.

The package we need to introduce:

// File package import java. io. byteArrayOutputStream; import java. io. file; import java. io. fileWriter; // toolkit import java. util. iterator; import java. util. list; // dom4j package import org. dom4j. attribute; import org. dom4j. document; import org. dom4j. export enthelper; import org. dom4j. element; import org. dom4j. io. outputFormat; import org. dom4j. io. SAXReader; import org. dom4j. io. XMLWriter;

1. convert the content of the XML file to String

/*** Doc2String ** convert the xml document content to String * @ return String * @ param Document */public static String doc2String (document) {String s = ""; try {// use the output stream to convert ByteArrayOutputStream out = new ByteArrayOutputStream (); // use GB2312 encoding OutputFormat format = new OutputFormat ("", true, "GB2312 "); XMLWriter writer = new XMLWriter (out, format); writer. write (document); s = out. toString ("GB2312");} catch (Exception ex) {ex. printStackTrace ();} return s ;}

2. convert a String in XML format to an XML Document

/*** String2Document * convert the String to a String in the Document * @ return * @ param s xml format */public static Document string2Document (String s) {Document doc = null; try {doc = incluenthelper. parseText (s);} catch (Exception ex) {ex. printStackTrace ();} return doc ;}

3. save the Document object as an xml file to your local device.

/*** Doc2XmlFile ** save the Document object as an xml file to the local device * @ return true: saved successfully. flase: failed * @ param filename saved file name * @ param document object to be saved */public static boolean doc2XmlFile (document Document, String filename) {boolean flag = true; try {/* write content in document into file * // The default is UTF-8 format, specified as "GB2312" OutputFormat format = OutputFormat. createPrettyPrint (); format. setEncoding ("GB2312"); XMLWriter writer = new XMLWriter (new FileWriter (new File (filename), format); writer. write (document); writer. close ();} catch (Exception ex) {flag = false; ex. printStackTrace ();} return flag ;}

4. Save the string in xml format as a local file. if the string format does not comply with the xml rules, an error is returned.

/*** String2XmlFile * saves the string in xml format as a local file. if the string format does not comply with the xml rules, an error is returned * @ return true: saved successfully. flase: failed * @ param filename saved file name * @ param str String to be saved */public static boolean string2XmlFile (String str, String filename) {boolean flag = true; try {Document doc = policenthelper. parseText (str); flag = doc2XmlFile (doc, filename);} catch (Exception ex) {flag = false; ex. printStackTrace ();} return flag ;}

5. load an xml document

/*** Load * load an xml Document * @ return: the Document object is returned successfully. if the return result is null * @ param uri file path */public static Document load (String filename) {Document document = null; try {SAXReader saxReader = new SAXReader (); document = saxReader. read (new File (filename);} catch (Exception ex) {ex. printStackTrace ();} return document ;}

6. Save the demo String as an xml file

/*** XmlWriteDemoByString * demonstrate saving String as an xml file */public void xmlWriteDemoByString () {String s = "";/** xml format Title"
 "No need to write */s ="
 
  
\ R \ n "+"
  
   
\ R \ n "+"
   
    
127.0.0.1
   \ R \ n "+"
   
    
21
   \ R \ n "+"
   
    
Cxl
   \ R \ n "+"
   
    
Longshine
   \ R \ n "+"
   \ R \ n "+"
   
    
50
   \ R \ n "+"
   \ R \ n "+"
   
    
10
   \ R \ n "+"
  \ R \ n "+"
 \ R \ n "; // Generate the file to string2XmlFile (s," xmlWriteDemoByString. xml "); // Generate the file to the string2XmlFile (s," classes/xmlWriteDemoByString. xml ");}

7. create a Document manually and save it as an XML file.

/*** Create a Document manually and save it as an XML file */public void xmlWriteDemoByDocument () {/** create a document object */Document document Document = incluenthelper. createDocument ();/** create config root node */Element configElement = document. addElement ("config");/** create an ftp node */configElement. addComment (" ftp configuration"); Element ftpElement = configElement. addElement ("ftp"); ftpElement. addattridian ("name", "DongDian");/** ftp attribute configuration */Element hostElement = ftpElement. addElement ("ftp-host"); hostElement. setText ("127.0.0.1"); (ftpElement. addElement ("ftp-port ")). setText ("21"); (ftpElement. addElement ("ftp-user ")). setText ("cxl"); (ftpElement. addElement ("ftp-pwd ")). setText ("longshine"); ftpElement. addComment ("maximum number of ftp connection attempts"); (ftpElement. addElement ("ftp-try ")). setText ("50"); ftpElement. addComment ("ftp connection attempt delay time"); (ftpElement. addElement ("ftp-delay ")). setText ("10");/** save Document */doc2XmlFile (document, "classes/xmlWriteDemoByDocument. xml ");}

8. demonstrate the value of a specific node for reading files

/*** Demonstrate the value of a specific node for reading files */public static void xmlReadDemo () {Document doc = load ("classes/xmlWriteDemoByDocument. xml "); // Element root = doc. getRootElement ();/** use xpath to search for all ftp nodes and output its name attribute value */List list = doc. selectNodes ("/config/ftp"); Iterator it = list. iterator (); while (it. hasNext () {Element ftpElement = (Element) it. next (); System. out. println ("ftp_name =" + ftpElement. attribute ("name "). getValue ();}/** get the name value directly using the attribute path */list = doc. selectNodes ("/config/ftp/@ name"); it = list. iterator (); while (it. hasNext () {Attribute attribute = (Attribute) it. next (); System. out. println ("@ name =" + attribute. getValue ();}/** directly obtain the ftp-host value of DongDian ftp */list = doc. selectNodes ("/config/ftp-host"); it = list. iterator (); Element hostElement = (Element) it. next (); System. out. println ("DongDian's ftp_host =" + hostElement. getText ());}

9. modify or delete a value or attribute

/** Delete the ftp-host node on the ftp node */ftpElement. remove (hostElement);/** delete the name attribute of the ftp node */ftpElement. remove (nameAttribute);/** modify the ftp-host value */hostElement. setText ("192.168.0.1");/** modify the value of the ftp node name attribute */nameAttribute. setValue ("ChiFeng ");


The above is the content for dom4j to operate xml files (all). For more information, see PHP Chinese website (www.php1.cn )!

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.