Convert XML to JavaBean using DOM4J and reflection mechanisms

Source: Internet
Author: User
Tags dateformat



Import Java.io.File;
Import Java.io.FileWriter;
Import Java.lang.reflect.Field;
Import Java.lang.reflect.Method;
Import Java.sql.Timestamp;
Import Java.text.DateFormat;
Import Java.text.SimpleDateFormat;
Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;

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;

/**
* Tool class for converting between XML and JavaBean
* @author
* @param <T>
*/
public class Beanxmlutils<t> {
private static DateFormat DF = new SimpleDateFormat ("Yyyy-mm-dd");
/**
* * @param obj Generic Object
* @param the list collection of Entitypropertys generic objects
* @param Encode XML custom encoding type (recommended with GBK)
* @param the path and file name of the Xmlpathandname XML file
*/
public void Writexmldocument (T obj, list<t> entitypropertys, String encode,string xmlpathandname) {
Long lasting = System.currenttimemillis ();//Efficiency detection
try {
XMLWriter writer = null;//declares an object that writes XML
OutputFormat format = Outputformat.createprettyprint ();
Format.setencoding (Encode);//Set the encoding format of the XML file
String FilePath = xmlpathandname;//Get file address
File File = new file (filePath);//Get Files
if (file.exists ()) {
File.delete ();
}
Create a new Student.xml file and add new content
Document document = Documenthelper.createdocument ();
String rootname = Obj.getclass (). Getsimplename ();//Get class name
Element root = document.addelement (Rootname + "s");//Add root node
Field[] Properties = Obj.getclass (). Getdeclaredfields ();//Get all the properties of an entity class
for (T T:entitypropertys) {
Recursive entities
Element secondroot = root.addelement (rootname);
Level Two node
for (int i = 0; i < properties.length; i++) {
Reflection Get Method
Method meth = T.getclass (). GetMethod ("Get" + properties[i].getname (). substring (0, 1). toUpperCase () + properties[i]. GetName (). substring (1));
Add an attribute to a level two node with the value of the corresponding property
Secondroot.addelement (Properties[i].getname ()). SetText (Meth.invoke (t). toString ());
}
}
Generating an XML file
writer = new XMLWriter (new FileWriter (file), format);
Writer.write (document);
Writer.close ();
Long lasting2 = System.currenttimemillis ();
System.out.println ("Write XML file end, time elapsed" + (lasting2-lasting) + "MS");
} catch (Exception e) {
SYSTEM.OUT.PRINTLN ("XML file Write Failed");
}

}
/**
* @param the path and address of the Xmlpathandname xmlpathandname XML file
* @param-T generic Object
* @return
*/
Public list<t> ReadXML (String objnodestr,string xmlstr, T t) {
Long lasting = System.currenttimemillis ();//Efficiency detection
list<t> list = new arraylist<t> ();//Create List collection
try {
File F = new file (xmlpathandname);//Read files
Saxreader reader = new Saxreader ();
Document doc = Reader.read (f);//DOM4J read
/* Document doc = null;
The following is the parsing of XML strings by the
doc = Documenthelper.parsetext (xmlpathandname); To convert a string to XML
*/
File F = new file (xmlpathandname);//Read files
Saxreader reader = new Saxreader ();
Document doc = Reader.read (f);//DOM4J read
Document doc = Documenthelper.parsetext (XMLSTR);
Element root = Doc.getrootelement ();//Get root node
Element Dataele = root.element ("Data"); Gets the child node under the root node data
Element Yhjzpbele = dataele.element (TR1); Gets the child node under the data node YHJZPB
Element foo;//Level Two node
Field[] Properties = T.getclass (). Getdeclaredfields ();//Get the properties of an instance
The Get method of the instance
Method Getmeth;
The set method of the instance
Method Setmeth;
System.out.println (T.getclass (). Getsimplename ());
String text = Yhjzpbele.gettext ();
System.err.println (text);
for (Iterator i = Root.elementiterator (OBJNODESTR); I.hasnext ();) {
Traverse the T.getclass (). Getsimplename () node
Foo = (Element) i.next ();//Next Level two node
t= (T) T.getclass (). newinstance ();//Get a new instance of the object
for (int j = 0; J < Properties.length; J + +) {
Traverse all grandchild nodes
The set method of the instance
Setmeth = T.getclass (). GetMethod ("set" + properties[j].getname (). substring (0, 1). toUpperCase () + properties[j]. GetName (). substring (1), Properties[j].gettype ());
Properties[j].gettype () is the parameter type of the Set method entry parameter (class type)
System.err.println (Properties[j].gettype ());
String proname = Properties[j].getname (). toUpperCase ();//class Property name string
Object setstr = Foo.elementtext (proname);
if (Properties[j].gettype () ==java.sql.timestamp.class && foo.elementtext (proname) = null) {
Timestamp ts = new Timestamp (Df.parse (Foo.elementtext (Proname)). GetTime ());
SETSTR = ts;
}
if (Properties[j].gettype () ==int.class) {
if (Foo.elementtext (proname) = null &&! "". Equals (Foo.elementtext (proname))) {
int Intts = Integer.parseint (Foo.elementtext (proname));
Setstr = Intts;
}else{
SETSTR = 0;
}
}
Setmeth.invoke (t, setstr);//The value of the corresponding node is stored
}
List.add (t);
}
} catch (Exception e) {
E.printstacktrace ();
}
Long lasting2 = System.currenttimemillis ();
SYSTEM.OUT.PRINTLN ("Read XML file end, time elapsed" + (lasting2-lasting) + "MS");
return list;
}

/*public static void Main (string[] args) {
String XML = new TestWebService (). ReadXML ("File/testbean.xml");
Beanxmlutils<xmlbean> beanxmlutils=new beanxmlutils<xmlbean> ();
Xmlbean testbean=new Xmlbean ();
List<xmlbean> list=beanxmlutils.readxml ("Record", Xml,testbean);
for (Xmlbean xb:list) {
System.out.println (Xb.getid ());
}
}*/
}

Convert XML to JavaBean using DOM4J and reflection mechanisms

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.