Be default, XiMpLe uses the Object's fully-qualified class name as the root
tag name of the XML. If you prefer to use an alternate tagname for the root
tag, then you must map the tag name to the Class of the Object to be
serialized. To do this, make a call to the addMapping(String, Class) method.
This will associate a tag name to a Class during serialization/deserialization.
ximple.addMapping("contact", Person.class);
So the XML output will become:
<contact>
<firstname>William</firstname>
<lastname>Rockpierre</lastname>
</contact>
Conversely, during deserialization, when the <contact>
root
element is parsed, it will instantiate an instance of the Person
class.
You can also customize the behaviour of XiMpLe to include and/or exclude methods
during serialization/deserialization. This provides you with greater control
as to which methods are called, in addition to the getter/setter methods,
that you wish to serialize/deserialize.
The Ximple
class has two methods to explicitly include or exclude
methods from serialization/deserialization:
addMethodToInclude(Class, String)
and
addMethodToExclude(Class, String)
, respectively.
For both methods, the first parameter specifies the Class where the method is declared
and the second parameter specifies the method name to include/exclude. The method
name is the full name as declared in the class. If a property you wish to
exclude during serialization/deserialization has a getter and a setter
method, then you must make two calls to addMethodToExclude(Class, String)
,
one for each method.
Using the Person
class defined above, if you did not want to serialize
the lastname, then you would initialize the Ximple
object as follows:
Ximple ximple = new Ximple();
ximple.addMethodExclude(Person.class, "getLastname");
Person person = new Person();
person.setFirstname("William");
person.setLastname("Rockpierre");
ximple.writeXml(person, new FileWriter("person.xml"));
The expected
person.xml
file would contain:
<Person>
<firstname>William</firstname>
</Person>