Dom4j reads, writes, modifies, and formats XML

Source: Internet
Author: User

Package Dom;

Import java. Io. file;
Import java. Io. fileoutputstream;
Import java. Io. filewriter;
Import java. util. iterator;
Import java. util. List;

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;

Import dom4jpackage. bdom4j;

/* Including reading, writing, modifying, and formatting XML by dom4j */

Public class dom4j {

Private void readxmlfile (string infile) throws exception {// read the XML file
Try {

File F = new file (infile );

Saxreader reader = new saxreader ();

Document Doc = reader. Read (f );

Element root = Doc. getrootelement ();

Element Foo;

For (iterator I = root. elementiterator ("datarow"); I. hasnext ();)

{Foo = (element) I. Next ();
/* System. Out. println ("name:" + Foo. elementtext ("name "));
System. Out. println ("Age:" + Foo. elementtext ("Age "));
System. Out. println ("Tel:" + Foo. elementtext ("tel "));
System. Out. println ("Gender:" + Foo. attributevalue ("gender "));*/

List list = (list) Foo. Elements ();
Iterator J = List. iterator ();
Int A = 1;
While (J. hasnext ())
{Element foo1 = (element) J. Next ();
// If (! = 1)
System. Out. println (foo1.gettext ());
// A ++;
}
/* While (J. hasnext ())
{Element foo1 = (element) J. Next ();
List list1 = (list) foo1.elements ();
Iterator J1 = list1.iterator ();
While (j1.hasnext ()){
Element foo11 = (element) j1.next ();
System. Out. println (foo11.gettext ());
}*/


}

} Catch (exception e ){

E. printstacktrace ();

}

}

Private void writexmlfile (string OUTFILE) throws exception {// write an XML file

}

// Create an XML document
Public int createxmlfile (string filename ){
/** Operation result returned. Table 0 failed, Table 1 succeeded */
Int returnvalue = 0;
/** Create a document object */
Document document = incluenthelper. createdocument ();
/** Create the root books of the XML document */
Element bookselement = Document. addelement ("books ");
/** Add a line of comment */
Bookselement. addcomment ("this is a test for dom4j, lx, 2008.12.11 ");
/** Add the first book node */
Element bookelement = bookselement. addelement ("book ");
/** Add the show attribute content */
Bookelement. addattribute ("show", "yes ");
/** Add a title node */
Element titleelement = bookelement. addelement ("title ");
/** Set content for title */
Titleelement. settext ("dom4j tutorials ");

/** Two books after similar completion */
Bookelement = bookselement. addelement ("book ");
Bookelement. addattribute ("show", "yes ");
Titleelement = bookelement. addelement ("title ");
Titleelement. settext ("Lucene studing ");
Bookelement = bookselement. addelement ("book ");
Bookelement. addattribute ("show", "no ");
Titleelement = bookelement. addelement ("title ");
Titleelement. settext ("Lucene in action ");

/** Add an owner node */
Element ownerelement = bookselement. addelement ("owner ");
Ownerelement. settext ("Liu X ");

Try {
/** Write the content in the document to the file */
Xmlwriter writer = new xmlwriter (New filewriter (new file (filename )));
Writer. Write (document );
Writer. Close ();
/** If the execution is successful, 1 is returned */
Returnvalue = 1;
} Catch (exception ex ){
Ex. printstacktrace ();
}

Return returnvalue;
}

/**
* Format XML documents and solve Chinese problems
*
* @ Param filename
* @ Return
*/
Public int formatxmlfile (string filename ){
Int returnvalue = 0;
Try {
Saxreader = new saxreader ();
Document document = saxreader. Read (new file (filename ));
Xmlwriter writer = NULL;
/** Format the output, with the same type as IE browsing */
Outputformat format = outputformat. createprettyprint ();
/** Specify XML encoding */
Format. setencoding ("GBK ");
Writer = new xmlwriter (New filewriter (new file (filename), format );
Writer. Write (document );
Writer. Close ();
/** If the execution is successful, 1 is returned */
Returnvalue = 1;
} Catch (exception ex ){
Ex. printstacktrace ();
}
Return returnvalue;
}

/**
* Modify the content in the XML file and save it as a new file. Master how to add, modify, and delete nodes in dom4j.
*
* @ Param filename
* Modifying object files
* @ Param newfilename
* Save the modification as a file.
* @ Return returns the operation result. Table 0 fails and table 1 is successful.
*/
Public int modixmlfile (string filename, string newfilename ){
Int returnvalue = 0;
Try {
Saxreader = new saxreader ();
Document document = saxreader. Read (new file (filename ));
/**
* One of the changes: if the show attribute in the book node is set to yes, It is changed to No.
*/
/** Search for objects using XPath first */
List list = Document. selectnodes ("/books/book/@ show ");
Iterator iter = List. iterator ();
While (ITER. hasnext ()){
Attribute attribute = (attribute) ITER. Next ();
If (attribute. getvalue (). Equals ("yes ")){
Attribute. setvalue ("no ");
}
}
/**
* Modify content 2: Change the owner item to lx and add the date node to the owner node. The content of the date node is.
* Add a property type for the date node.
*/
List = Document. selectnodes ("/books/owner ");
Iter = List. iterator ();
If (ITER. hasnext ()){
Element ownerelement = (element) ITER. Next ();
Ownerelement. settext ("look ");
Element dateelement = ownerelement. addelement ("date ");
Dateelement. settext ("2004-09-11 ");
Dateelement. addattribute ("type", "calendar ");
}

/** Modify content 3: If the title content is dom4j tutorials, delete the node */
List = Document. selectnodes ("/books/book ");
Iter = List. iterator ();
While (ITER. hasnext ()){
Element bookelement = (element) ITER. Next ();
Iterator = bookelement. elementiterator ("title ");
While (iterator. hasnext ()){
Element titleelement = (element) iterator. Next ();
If (titleelement. gettext (). Equals ("dom4j tutorials ")){
Bookelement. Remove (titleelement );
}
}
}

Try {
/** Write the content in the document to the file */
// Xmlwriter writer = new xmlwriter (New filewriter (new file (
// Newfilename )));
Xmlwriter writer = new xmlwriter (New fileoutputstream (
Newfilename ));

Writer. Write (document );
Writer. Close ();
/** If the execution is successful, 1 is returned */
Returnvalue = 1;
} Catch (exception ex ){
Ex. printstacktrace ();
}

} Catch (exception ex ){
Ex. printstacktrace ();
}
Return returnvalue;
}

Public static void main (string [] ARGs) throws exception {

Dom4j dom = new dom4j ();
Bdom4j BD = new bdom4j ();
/* Bd. openxml ("newdom4j. xml ");
System. Out. println (BD. getelementvalue ("owner "));
BD. setelementvalue ("owner", "GG ");
BD. addnodefromroot ("price", "20 ");
BD. savexml ("newdom4j. xml ");*/
System. Out. println ("starting to read the input. xml file ");
Dom. readxmlfile ("demo. xml ");
// Dom. readxmlfile ("dom4j. xml ");
System. Out. println ("read finished, start to write the output. xml file ");
// Dom. createxmlfile ("dom4j. xml ");
// Dom. formatxmlfile ("dom4j. xml ");
// Dom. modixmlfile ("dom4j. xml", "newdom4j. xml ");
// Dom. formatxmlfile ("demo. xml"); // The New fileoutputstream (
// Newfilename) write the file
}
}

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.