問題描述
有哪些開源庫可用于將 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 值對象?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!