JDom - can an object be parsed into xml?
문제
Im using JDom for creating and retrieving XML messages. I would like to encode an object into xml, say I have a User object class this
class User
{
int id;
String name;
}
User user;
Is there a method that will automatically parse an object like this into an XML document or do I have to manually set the elements of the XML document?
해결책
XStream can do that for you. http://x-stream.github.io/
XStream is a simple library to serialize objects to XML and back again.
다른 팁
As @Ashwini Raman mentions, you can use XStream,
If you need the Object to be converted to a JDOM Element before its output then here's an example of the code you would need.
//Here I create a new user, you will already have one!
User u = new User();
XStream xStream = new XStream();
//create an alias for User class otherwise the userElement will have the package
//name prefixed to it.
String alias = User.class.getSimpleName();
//add the alias for the User class
xStream.alias(alias, User.class);
//create the container element which the serialized object will go into
Element container = new Element("container");
//marshall the user into the container
xStream.marshal(u, new JDomWriter(container));
//now just detach the element, so that it has no association with the container
Element userElement = (Element) container.getChild(alias).detach();
//Optional, this prints the JDOM Element out to the screen, just to prove it works!
new XMLOutputter().output(userElement, System.out);
As mentioned in the code you need to create a "container" element to put the object into.
you then detach
the marshalled JDOMElement from the container (There may be a way of skipping this step, if there is someone please feel free to edit this!) Then the JDOM Element userElement
is ready to use.
The Alias
String alias = User.class.getSimpleName();
xStream.alias(alias, User.class);
Is necessary ortherwise the root User Element will have the package name prefixed to it
e.g.
<org.mypackage.User>....</org.mypackage.User>
using the alias ensures that the element will just be the class name without the package name
derived from User.class.getSimpleName()