JDom - 可以将对象解析为xml吗?

时间:2012-02-28 10:19:15

标签: java jdom

我使用JDom创建和检索XML消息。我想将一个对象编码为xml,比如说我有一个User对象类

class User
{
    int id;
    String name;
}

User user;

是否有一种方法可以自动将这样的对象解析为XML文档,还是必须手动设置XML文档的元素?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

正如@Ashwini Raman所提到的,你可以使用XStream,

如果您需要在输出之前将Object转换为JDOM元素,那么这里是您需要的代码示例。

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

如代码中所述,您需要创建一个“容器”元素来放置对象。 然后从容器中detach编组的JDOMElement(可能有一种方法可以跳过这一步,如果有人请随意编辑它!)然后JDOM元素userElement就可以使用了。

别名

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

有必要的是,根用户元素将包装名称作为前缀

e.g。

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

使用别名可确保元素只是没有包名称的类名

派生自User.class.getSimpleName()