The JavaBean-XML component allows you to easily convert JavaBeans to XML.

Source: Internet
Author: User
Tags xml parser
Complex Code To allow your JavaBeans to control the conversion of XML files. This article shows how to use Write components to convert JavaBeans to XML files.

To flexibly meet changes in web applications and web services requirements, the ease and scalability of Java and XML makes them an ideal choice to solve this problem. SAX (Simple API for XML), Dom (document. nbspobject model), XSL (Extensible Stylesheet Language), XSLT (XSL transformations), Soap (Simple Object Access Protocol), and BML (bean Markup Language) are related technologies in the XML field. This article combines the lightweight and extensible Java and XML advantages, but developers do not need to understand the above-mentioned technologies.

Use remote method call (RMI) in Java distributed applications, instead of directly using the underlying socket or other network connection code. The EJB technology also frees developers from underlying mechanisms such as transaction, recovery, and activation. Similarly, using the JavaBean-XML ing component in this article, developers do not need to directly process XML-related APIs.

Component Compilation

The beanxmlmapping component converts Javabean to XML files. With the internal saving mechanism of JavaBean, the XML Parser and Dom APIs, you can write the toxml () method to implement conversion from Javabean to XML files, and fromxml () method to convert an XML file to a JavaBean.

List 1 shows a possible implementation of the beanxmlmapping component.ProgramJava objects in XML class library. Of course, you can also use other APIs to implement beanxmlmapping components. Jox is used here because it is relatively simple and can be reused.

List 1 beanxmlmapping Components

Import com. wutka. Jox .*;

Import java. Io. bytearrayinputstream;

Import java. Io. bytearrayoutputstream;

Import java. Io. ioexception;

Public class beanxmlmapping {

/**

* Retrieves a bean object for

* Received XML and matching Bean class

*/

Public static object fromxml (string XML, class classname ){

Bytearrayinputstream xmldata = new bytearrayinputstream (XML. getbytes ());

Joxbeaninputstream joxin = new joxbeaninputstream (xmldata );

Try {

Return (object) joxin. readobject (classname );

} Catch (ioexception exc ){

Exc. printstacktrace ();

Return NULL;

} Finally {

Try {

Xmldata. Close ();

Joxin. Close ();

} Catch (exception e ){

E. printstacktrace ();

}

}

}

/**

* Returns an XML document. nbspstring for the specified ed Bean

*/

Public static string toxml (Object bean ){

Bytearrayoutputstream xmldata = new bytearrayoutputstream ();

Joxbeanoutputstream joxout = new joxbeanoutputstream (xmldata );

Try {

Joxout. writeobject (beanname (bean), bean );

Return xmldata. tostring ();

} Catch (ioexception exc ){

Exc. printstacktrace ();

Return NULL;

} Finally {

Try {

Xmldata. Close ();

Joxout. Close ();

} Catch (exception e ){

E. printstacktrace ();

}

}

}

/**
* Find out the Bean class name
*/
Private Static string beanname (Object Bean) {
string fullclassname = bean. getclass (). getname ();
string classnametemp = fullclassname. substring (
fullclassname. lastindexof (". ") + 1,
fullclassname. length ()
);
return classnametemp. substring (0, 1)
+ classnametemp. substring (1);

}

Beanxmlmapping class provides two methods to achieve mutual conversion from Javabean to XML files:

Toxml (): generate the XML format string corresponding to the bean instance

Fromxml (): Create a bean instance using a string in XML format

Use of componentsList 2 shows the JavaBean named accounthistorycontext. The toxml () and fromxml () methods in this class simply call the toxml () and fromxml () Methods of the beanxmlmapping component.

List 2 accounthistorycontext Bean

Public class accounthistorycontext {

Private string datefrom;

Public String getdatefrom () {return datefrom ;}

Public void setdatefrom (string s) {datefrom = s ;}

...

// Other attributes with their get and set methods

Public String toxml (){

Return beanxmlmapping. toxml (this );

}

Public static accounthistorycontext fromxml (string XML ){

Return (accounthistorycontext)

Beanxmlmapping. fromxml (

XML, accounthistorycontext. Class );

}

}

Figure 1 shows the ing between a general JavaBean class and its corresponding XML file

Convert from Javabean to XML

The first line of the XML file is the declaration of the XML version. In the above example, it is set to version 1.0 (<? XML version = "1.0" encoding = "ISO-8859-1"?> ).

The following line defines the root contacts of the XML file. In this example, the Class Name of JavaBean (<bean>) is used ).

Next we will define the child nodes of the nodes. The node name is the attribute that can be accessed by the get method in bean. If the attribute is of the basic type (such as string or INT), the node is directly generated using the attribute name. If the attribute is another bean, a corresponding nested node is generated.

Figure 2 shows the contactinfo class instance, contactinfo class, and XML file generated by the toxml () method.

Convert from XML to JavaBean

When reading an XML file, the root node name, node attribute, and nested node will respectively establish a ing relationship with the bean, set method, and nested beans. Therefore, to complete the ing, you must provide the default constructor for each bean and the Set Method (basic type or nested bean) for each attribute ).

Figure 3 shows the contactinfo XML file, the corresponding contactinfo class, And the contactinfo class instance generated using the fromxml () method.

Example

Let's take a look at an example of using the beanxmlmapping component. The example consists of an XML file, a JavaBean class, and an online bank snapshot. You can download the source code of the example from here.

Figure 4 online bank history account page.

Figure 5 shows the class chart of accounthistory. List 3 shows the XML file generated by the class through the toxml () method.

List 3 historical accounting information encapsulated in XML

<? XML version = "1.0" encoding = "ISO-8859-1"?>

<Accounthistory>

<Transactionlist>

<Transaction>

<Deposit> </deposit>

<Withdraw>-1,150.00 </withdraw>

<Date> 3/10/2002 </date>

<Description> check number: 213 </description>

<Balance> $3,340.50 </balance>

</Transaction>

<Transaction>

<Deposit> </deposit>

<Withdraw>-151.50 </withdraw>

<Date> 3/7/2002 </date>

<Description> ATM withdrawal 350 San Jose Ca </description>

<Balance> $3,189.00 </balance>

</Transaction>

<Transaction>

<Deposit >$ 4,060.40 </deposit>

<Withdraw> </withdraw>

<Date> 3/5/2002 </date>

<Description> ach deposit-mycompany </description>

<Balance> $7,249.40 </balance>

</Transaction>

<Transaction>

<Deposit> </deposit>

<Withdraw>-20.00 </withdraw>

<Date> 2/26/2002 </date>

<Description> JC's BBQ and deli San Jose Ca </description>

<Balance> $7,229.40 </balance>

</Transaction>

</Transactionlist>

<Accounthistorycontext>

<Account>

<Holder> Paulo Caroli
<Type> checkings </type>

<Number> 316614-10 </number>

</Account>

<Dateto> Monday, March 11,200 2 </dateto>

<Datefrom> Monday, February 25,200 2 </datefrom>

</Accounthistorycontext>

</Accounthistory>

Figure 6 sequence diagram shows how to find the class accounthistory and call its toxml () method.

Figure 7 online bank request history account page. The account and date are displayed on this page. list 4 encapsulates the display information in XML.

List 4 historical accounting request information encapsulated in XML

<? XML version = "1.0" encoding = "ISO-8859-1"?>

<Accounthistorycontext>

<Account>

<Holder> Paulo Caroli
<Type> checkings </type>

<Number> 316614-10 </number>

</Account>

<Dateto> Monday, March 11,200 2 </dateto>

<Datefrom> Monday, February 25,200 2 </datefrom>

</Accounthistorycontext>

The fromxml () method of the accounthistorycontext class converts the XML file to the corresponding accounthistorycontext class object.

It is so simple that there is no need for complex code to implement mutual conversion from Javabean to XML files. Program developers can use the beanxmlmapping component without worrying about the underlying XML-related class libraries.

Original article:

Http://www.javaworld.com/javaworld/javatips/jw-javatip138.html?color=black=#/color]

Matrix open-source technology is translated and released with javaworld authorization.

If youArticleIf you have any comments or suggestions, please go to the matrix forum to post your comments.

Note: If you are interested in the matrix translation article series, click oreilly and javaworld to view details.

You can also click-flashspy to view the translation author's details.

Original article: http://www.javaworld.com/javaworld/javatips/jw-javatip138.html

Forum discussion: http://www.matrix.org.cn/forum.asp

More technical articles: http://www.matrix.org.cn/article.asp

Matrix Java Portal: http://www.matrix.org.cn

Address: http://www.matrix.org.cn/article/473.html

If you are licensed to repost this article, you must mark the original address of matrix in a prominent position and link it to the original page to view detailed copyright descriptions.

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.