2012-02-28 46 views
0

我使用JDom创建和检索XML消息。我想编码对象转换为XML,说我有一个用户对象类此JDom - 可以将对象解析为xml吗?

class User 
{ 
    int id; 
    String name; 
} 

User user; 

是否有将自动解析这样一个对象到XML文档或我必须手动设置元素的方法的XML文件?

回答

2

XStream可以为您做到这一点。 http://x-stream.github.io/

XStream是一个简单的库,用于将对象序列化为XML并返回。

+0

1导出提XStream的包名称

reevesy 2012-02-28 11:44:16

0

由于@Ashwini拉曼提到,如果你需要的对象到其输出之前被转换成JDOM元素那么这里就是你需要的代码的例子,你可以使用XStream的,

//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); 

正如代码中所提到的,您需要创建一个“容器”元素来放入对象。 然后你从容器中调用JDOMElement detach(可能有一种跳过这一步的方法,如果有人请随时编辑这个!)然后JDOM元素userElement已准备好使用。

别名

String alias = User.class.getSimpleName(); 
    xStream.alias(alias, User.class); 

是必要ortherwise根用户元件将具有包名称前缀它

例如

<org.mypackage.User>....</org.mypackage.User> 

使用别名确保元件将只是类名不脱离User.class.getSimpleName()