Java parses an object into an XML file

Source: Internet
Author: User

Let's take a look at an example ~~~

Here is a piece of my test code:

Package COM. domain; import Java. SQL. timestamp; import Java. util. arraylist; import Java. util. list; import Org. dreamer. parse. XML. xmlbean; import Org. dreamer. parse. XML. xmlsupport; import COM. pan. action. product; public class xmltest {/*** @ Param ARGs */public static void main (string [] ARGs) {// todo auto-generated method stubproduct Product = new product (); product. setaddtime (New timestamp (100); product. setbidprice (12d); product. setdescription ("product description"); product. setid (1); product. setimg ("image"); product. setname ("iphone5"); product. setprice (3000d); product. setstock (12); product. setsupplier ("us"); Human human = new human (); Human. setproduct (product); List list = new arraylist (); list. add (product); list. add (product); list. add (product); list. add (human); system. out. println (New xmlsupport (). parsecollection (list ));}}

After assigning values to the bean, run the following command to get the result:

<? XML version = "1.0" encoding = "UTF-8"?> <Items> <product> <ID> 1 </ID> <Name> iphone5 </Name> <description> product description </description>  image </img> <stock> 12 </stock> <bidprice> 12.0 </bidprice> <price> 3000.0 </price> <weight> null </weight> <unit> null </Unit> <supplier> us </supplier> <addtime> 08:00:00. 1 </addtime> </product> <ID> 1 </ID> <Name> iphone5 </Name> <description> product description </description>  image </img> <stock> 12 </stock> <bidprice> 12.0 </bidprice> <price> 3000.0 </price> <weight> null </weight> <unit> null </unit> <supplier> USA </supplier> <addtime> 08:00:00. 1 </addtime> </product> <ID> 1 </ID> <Name> iphone5 </Name> <description> product description </description>  image </img> <stock> 12 </stock> <bidprice> 12.0 </bidprice> <price> 3000.0 </price> <weight> null </weight> <unit> null </unit> <supplier> USA </supplier> <addtime> 08:00:00. 1 </addtime> </product> 

We can see that the collection is parsed and the objects in the object are also parsed. It can be parsed infinitely.

Next let's look at the implementation class:

Core code:

Xmlbean. Java (the main function of this class is to use reflection to obtain information about objects)

Package Org. dreamer. parse. XML; import Java. lang. reflect. field; import Org. dreamer. parse. dao. idataparse; import Org. dreamer. parse. util. nodeutil; import Org. dreamer. parse. util. typecollection; public class xmlbean implements idataparse {Public String getstring (Object object) {// Class Object Class Cl = object. getclass (); // column name string domname = Cl. getsimplename (); // field array field [] fields = Cl. getdeclaredfields (); // information storage object stringbuffe R sb = new stringbuffer (); sb. append ("<" + domname + "> \ r \ n"); // The traversal value is for (field: fields) {// The field can be accessed. setaccessible (true); try {object value = field. get (object) = NULL? "Null": field. Get (object); If (! New typecollection (). Check (value) & value! = NULL) {sb. append (getstring (value); continue;} sb. append (nodeutil. merge (field. getname (), value);} catch (exception e) {e. printstacktrace () ;}} sb. append ("</" + domname + "> \ r \ n"); return sb. tostring () ;}public string tostring () {return getstring (this );}}

Let's take a look at the support class,

The Support class encapsulates xmlbean.

Can combine and combine a single object

Xmlbean. Java

Package Org. dreamer. parse. XML; import Java. util. collection; import Org. dreamer. parse. dao. idatasupport; import Org. dreamer. parse. util. nodeutil;/*** XML parsing Support class * @ author Pan **/public class xmlsupport implements idatasupport {// The default name private string nodename = "items" when setting "; /*** to customize the node name, you must override this method * @ Param nodename */Public void setnodename (string nodename) {This. nodename = nodename;} Public String getnodenam E () {return nodename;}/*** parses the object into XML */Public String parsestring (Object object) {xmlbean xml = new xmlbean (); stringbuffer sb = new stringbuffer (); // append description header sb. append ("<? XML version = \ "1.0 \" encoding = \ "UTF-8 \"?> \ R \ n "); return sb. append (XML. getstring (object )). tostring ();}/*** parses the object set into XML */Public String parsecollection (Collection collection) {stringbuffer sb = new stringbuffer (); sb. append ("<? XML version = \ "1.0 \" encoding = \ "UTF-8 \"?> \ R \ n "); sb. append ("<" + nodename + "> \ r \ n"); xmlbean xml = new xmlbean (); For (Object object: Collection) {sb. append (XML. getstring (object);} sb. append ("</" + nodename + "> \ r \ n"); return sb. tostring ();}}

The next step is the util class, and the role of util is not small.

Datahelper. Java (this class can or can not be used, mainly to determine a type)

Package Org. dreamer. parse. util; import Java. SQL. timestamp; public class datahelper {/*** check whether the data type is string or timestamp * @ Param object * @ return */public static Boolean check (Object object) {return object instanceof string | object instanceof timestamp ;}}

Nodeutil. Java is used to generate node labels.

Package Org. dreamer. parse. util;/*** node merging tool class * @ author Pan **/public class nodeutil {public static string Merge (string node, object Value) {stringbuffer sb = new stringbuffer (); SB. append ("<" + node + ">"); sb. append (value); sb. append ("</" + node + "> \ r \ n"); return sb. tostring ();}}

Typecollection. Java
This class is also very important, mainly to determine whether the parsed field is an object. If it is an object, you must call recursive parsing.

Package Org. dreamer. parse. util; import Java. lang. reflect. field; import Java. SQL. timestamp;/*** basic type set * @ author Pan **/public class typecollection {/*** basic data type package class */private integer; private double double1; private float float1; private long long1; private string; private character; private Boolean boolean1; private short short1; private timestamp; /*** check whether the object is of the basic data type * @ Param object * @ return */Public Boolean check (Object object) {If (Object = NULL) return false; // obtain the field set of the current class object field [] fields = This. getclass (). getdeclaredfields (); For (field: fields) {// set the field to access field. setaccessible (true); // obtain the field type to compare if (field. getType (). getname (). equals (object. getclass (). getname () {return true ;}} return false ;}}

The above shows a complete XML parsing process.

The above code is extended from the dreamer framework. If you are interested, please refer to the dreamer area of my blog.

If you are interested, you can ask for the source code from me.

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.