Java operation XML file dom4j

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.
Today, let's talk about using dom4j in Java to operate XML files.

The package we need to introduce:

// 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. documenthelper;
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 XML document content to string
* @ Return string
* @ Param document
*/
Public static string doc2string (document)
{
String S = "";
Try
{
// Use the output stream for conversion
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 string to document
* @ Return
* @ Param s string in 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: name of the file to be saved
* @ Param document the document object to be saved
*/
Public static Boolean doc2xmlfile (document, string filename)
{
Boolean flag = true;
Try
{
/* Write the content in the document to the 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
* 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.
* @ Return true: saved successfully. flase: failed.
* @ Param filename: name of the file to be saved
* @ Param STR the string to be saved
*/
Public static Boolean string2xmlfile (string STR, string filename)
{
Boolean flag = true;
Try
{
Document Doc = incluenthelper. 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, and null is returned if the document object fails to be returned.
* @ Param URI file path
*/
Public static document load (string filename)
{
Document document = NULL;
Try
{
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 = "";
/** Title in XML format "<? XML version = '1. 0' encoding = 'gb2312 '?> "No need to write */
S = "<config> \ r \ n"
+ "<FTP name = 'dongdian '> \ r \ n"
+ "<FTP-host> 127.0.0.1 </ftp-host> \ r \ n"
+ "<FTP-port> 21 </ftp-port> \ r \ n"
+ "<FTP-user> CXL </ftp-user> \ r \ n"
+ "<FTP-PWD> longshine </ftp-PWD> \ r \ n"
+ "<! -- Maximum number of FTP connection attempts --> \ r \ n"
+ "<FTP-Try> 50 </ftp-Try> \ r \ n"
+ "<! -- FTP connection attempt Delay Time --> \ r \ n"
+ "<FTP-delay> 10 </ftp-delay> \ r \ n"
+ "</Ftp> \ r \ n"
+ "</Config> \ r \ n ";
// Generate the file to the directory where the classes folder is located
String2xmlfile (S, "xmlwritedemobystring. xml ");
// Generate the file to the classes folder
String2xmlfile (S, "classes/xmlwritedemobystring. xml ");
}

7. Create a document manually and save it as an XML file.

/**
* Demonstrate creating a document manually and saving it as an XML file
*/
Public void xmlwritedemobydocument ()
{
/** Create a document object */
Document document = incluenthelper. createdocument ();
/** Create a 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 reading the value of a specific node of a file
*/
Public static void xmlreaddemo ()
{
Document Doc = load ("classes/xmlwritedemobydocument. xml ");
// Element root = Doc. getrootelement ();
/** Use XPath to search for all FTP nodes and output their name attribute values */
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 ());
}
/** Directly use the attribute path to get the name value */
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/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 an FTP-host node from an FTP node */
Ftpelement. Remove (hostelement );
/** Delete the name attribute of an 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 ");

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.