Implementing XML information to Java Bean transformation

Source: Internet
Author: User
Tags add object return string unique id
Xml

This article is mainly about using the Commons-betwixt component to implement the transformation of XML information to Java Bean, the core class to achieve this function is Beanreader, if you look at Betwixt source code, you will find

public class Beanreader extends digester{}

If you look at the source code of the Beanreader, Betwixt is actually invoking the parse method of digester this class when dealing with Xml-->javabean transformations. But in addition to this way can realize the function of transformation, Beanreader itself has some new mechanisms for the transformation of XML, improve the Digester many lack of functionality, so that the transformation more convenient.

First, take a look at the process by which Beanreader completely transforms using the Digester parse method. (actually feel that it is digester how to deal with the transformation more appropriate)

1. XML information

<address-book>
<person id= "1" category= "acquaintance" try= "would be ignored" >
<name>Gonzo</name>
<email type= "Business" >gonzo@muppets.com</email>
<gender result= "The whole tag would be ignored" >male</gender>
</person>
<person id= "2" category= "Rolemodel" >
<name>Kermit</name>
<email type= "Business" >kermit@muppets.com</email>
<email type= "Home" >kermie@acme.com</email>
</person>
</address-book>

2. Define entity Objects person and AddressBook

Import Java.util.HashMap;
Import Java.util.Iterator;
public class Person {
private int id;
Private String category;
private String name;
Private HashMap emails = new HashMap ();

/**
* A Unique ID for this person. Note that the digester automatically
* Converts the ID to an integer.
*/
public void setId (int id) {
This.id = ID;
}

public void Setcategory (String category) {
this.category = category;
}

public void SetName (String name) {
THIS.name = name;
}

/** we assume only one email for each type ... * *
public void Addemail (string type, string address) {
Emails.put (type, address);
}


public void print () {
System.out.println ("Person #" + ID);
System.out.println ("category=" + category);
System.out.println ("name=" + name);

for (Iterator i = Emails.keyset (). iterator (); I.hasnext ();) {
String type = (string) i.next ();
String address = (string) emails.get (type);

System.out.println ("Email (type" + Type + "):" + address);
}

}

Import Java.util.Iterator;
Import java.util.LinkedList;

public class AddressBook {
LinkedList person = new LinkedList ();

Public LinkedList Getperson () {
return person;
}
public void Addperson (person p) {
Person.addlast (P);
}

public void print () {
System.out.println ("Address Book has" + person.size () + "entries");

for (Iterator i = Person.iterator (); I.hasnext ();) {
Person P = (person) i.next ();
P.print ();
}
}

3. Realize transformation function

public class addressbookdigester{
public static void Main (string[] args) throws IOException, Saxexception, introspectionexception{

Create a Beanreader instance
Beanreader reader = new Beanreader ();
Create a AddressBook instance and press it onto the top of the stack.
AddressBook book = new AddressBook ();
Reader.push (book);
Add rules
Addrules (reader);

Reader.parse (New File ("Examples.xml"));
Book.print ();

}
private static void Addrules (Beanreader d) {
When you encounter <person>, create an instance of the class person and press it onto the top of the stack
D.addobjectcreate ("Address-book/person", Person.class);
The properties of the <person> label and the property setting method of the Person class object on the top of the stack are mapped according to their respective names (for example, the
The Label property ID is mapped with the property setting method SetID, the Label property category is mapped to the property set method Setcategory, and then the value of the property is passed to the execution phase
should be the method.
If a label property cannot find the appropriate property setting method by name, the Label property is ignored (such as the first <person> try of the Example.xml
Sex).
D.addsetproperties ("Address-book/person");
Invokes the Addperson method of the second stack top object (addressbook instance), with the object of the Stack object (person instance) as a parameter
D.addsetnext ("Address-book/person", "Addperson");
When you encounter the child element <name> of <person>, call the SetName method of the Stack top object (person instance).
The first parameter of the Addcallmethod method here is the rule, the second parameter is the name of the method, and the third is the number of arguments (0 o'clock, which means that there is only one argument
, and the value of the parameter is the content of the element)
D.addcallmethod ("Address-book/person/name", "SetName", 0);
When you encounter the child element <email> of <person>, call the Addemail of the stack top object (person instance)
method, the Addemail method has two parameters, from the value of the property type of <email> and the contents of <email> itself.
The first parameter of the Addcallparam method here is the rule, the second parameter indicates the ordinal of the invoked method (Addemail) parameter, and the third is the argument is a string
Refers to the name of the attribute)
D.addcallmethod ("Address-book/person/email", "Addemail", 2);
D.addcallparam ("Address-book/person/email", 0, "type");
D.addcallparam ("Address-book/person/email", 1);
}
}

The results of the operation are as follows:

Address Book has 2 entries
Person #1
Category=acquaintance
Name=gonzo
Email (type business): gonzo@muppets.com
Person #2
Category=rolemodel
Name=kermit
Email (type business): kermit@muppets.com
Email (type Home): kermie@acme.com

Second, take a look at the way to configure the transformation properties without using the Digester Add***method () method.

1. Defining entity Classes

public class Personbean {

private String name;
private int age;

/** Need to allow beans to be created via reflection * *
Public Personbean () {}

Public Personbean (String name, int age) {
THIS.name = name;
This.age = age;
}

Public String GetName () {
return name;
}

public void SetName (String name) {
THIS.name = name;
}

public int getage () {
return age;
}

public void Setage (int age) {
This.age = age;
}

Public String toString () {
Return "Personbean[name= '" + name + "', age= '" + Age + "']";
}
}

2.person.xml file

<beans>
<personbean>
<age>22</age>
<name>luna</name>
</personbean>
</beans>
3. Realize transformation function

Import Java.io.StringReader;
Import Org.apache.commons.betwixt.io.BeanReader;
public class Readapp {

public static final void main (String args[]) throws exception{

Initialize and configure the Beanreader
Beanreader reader = new Beanreader ();
Reader.getxmlintrospector (). GetConfiguration ()
. Setattributesforprimitives (FALSE);
Reader.getbindingconfiguration (). Setmapids (false);
Register the Bean and tell Betwixt to convert the XML into what bean
Reader.registerbeanclass ("Personbean", Personbean.class);
Get an object and print
Personbean person = (Personbean) reader.parse (New File ("person.xml");
SYSTEM.OUT.PRINTLN (person);
}

}

Run Result:
Personbean[name= ' Luna ', age= ' 22 ']

Description of the points:

The parse () of the Digester class is the core approach to the transformation of XML to JavaBean, the biggest difference being that the former tells the Beanreader transformation step through the detailed add*** () method, while the latter is the Registerbeanclass () Registers the Bean object type that will be converted into, and the method call in which the beanreader automatically goes by number. The latter can also convert only one Bean object at a time, and the Togolese object can be manipulated using an iterative approach.

The former applies to the add*** () step-by-step setting of the transformation steps when the bean type and specific attributes are already known, and if the resulting object is unknown, the property is known only if the result is known. This is the time to use Registerbeanclass () in the latter method to register the class to Betwxit, the rest of the function, this component can be automatically completed.




Related Article

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.