如何将XML转换为Java值对象? [英] How do I convert XML into a java value object?

查看:73
本文介绍了如何将XML转换为Java值对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么样的开源库可用于将XML转换为Java值对象?

What kind of open-source libraries are available to convert XML into a java value object?

在.Net中,有一种方法可以通过xml序列化和属性轻松地做到这一点.我会想象在Java中有一些并行之处.我知道如何使用DOM或SAX解析器执行此操作,但是我想知道是否有更简单的方法.

In .Net, there is a way to easily do this with xml serialization and attributes. I would imagine there some parallel in java. I know how to do this with a DOM or SAX parser, but I was wondering if there was an easier way.

我有一个预定义的XML格式,看起来像这样.

I have a predefined XML format that looks something like this.

<FOOBAR_DATA>
  <ID>12345</ID>
  <MESSAGE>Hello World!</MESSAGE>
  <DATE>22/04/2009</DATE>
  <NAME>Fred</NAME>
</FOOBAR_DATA>

在.Net中,我可以执行类似的操作将对象绑定到数据.

In .Net, I can do something like this to bind my object to the data.

using System;
using System.Xml.Serialization;

    namespace FooBarData.Serialization
    {
      [XmlRoot("FOOBAR_DATA")]
      public class FooBarData
  {
    private int _ID = 0;
    [XmlElement("ID")]
    public int ID
    {
      get { return this._ID; }
      set { this._ID = value; }
    }

    private string _Message = "";
    [XmlElement("MESSAGE")]
    public string Message
    {
      get { return this._Message; }
      set { this._Message = value; }
    }

    private string _Name = "";
    [XmlElement("NAME")]
    public string Name
    {
      get { return this._Name; }
      set { this._Name = value; }
    }

    private Date _Date;
    [XmlElement("DATE")]
    public Date Date
    {
      get { return this._Date; }
      set { this._Date= value; }
    }

    public FooBarData()
    {
    }
  }
}

我想知道是否有一种使用注释的方法,类似于.Net或Hibernate,它将允许我将值对象绑定到预定义的XML.

I was wondering if there was a method using annotations, similar to .Net or perhaps Hibernate, that will allow me to bind my value object to the predefined-XML.

推荐答案

我特别喜欢 XStream 与JAXB相比-与JAXB不同,XStream不需要您具有XSD.如果您有少数几个要序列化和反序列化为XML的类,而又无需创建XSD,运行jaxc从该模式生成类等繁琐的工作,那太好了.另一方面,XStream很漂亮轻巧.

I like XStream alot, especially compared to JAXB - unlike JAXB, XStream doesn't need you to have an XSD. It's great if you have a handful of classes you want to serialize and deserialize to XML, without the heavy-handed-ness of needing to create a XSD, run jaxc to generate classes from that schema, etc. XStream on the other hand is pretty lightweight.

(当然,在很多情况下,JAXB都是合适的,例如,当您拥有适合这种情况的预先存在的XSD时...)

(Of course, there are plenty of times where JAXB is appropriate, such as when you have a pre-existing XSD that fits the occasion...)

这篇关于如何将XML转换为Java值对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆