xml JAXB:如何编组列表中的对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3683598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 13:16:54  来源:igfitidea点击:

JAXB: How to marshal objects in lists?

xmljaxbarraylistunmarshalling

提问by rmv

Perhaps a stupid question: I have a Listof type <Data>which I want to marshal into a XML file. This is my class Databasecontaining an ArrayList...

也许是一个愚蠢的问题:我有一个List类型<Data>,我想将其编组到 XML 文件中。这是我的课程,Database其中包含ArrayList...

@XmlRootElement
public class Database
{
    List<Data> records = new ArrayList<Data>();

    public List<Data> getRecords()                   { return records; }
    public void       setRecords(List<Data> records) { this.records = records; }
}

...and this is class Data:

...这是类数据:

// @XmlRootElement
public class Data 
{
    String name;
    String address;

    public String getName()            { return name;      }
    public void   setName(String name) { this.name = name; }

    public String getAddress()               { return address;         }
    public void   setAddress(String address) { this.address = address; }
}

Using the following test class...

使用以下测试类...

public class Test
{
    public static void main(String args[]) throws Exception
    {
        Data data1 = new Data();
             data1.setName("Peter");
             data1.setAddress("Cologne");

        Data data2 = new Data();
             data2.setName("Mary");
             data2.setAddress("Hamburg");

        Database database = new Database();
                 database.getRecords().add(data1);
                 database.getRecords().add(data2);

        JAXBContext context = JAXBContext.newInstance(Database.class);
        Marshaller marshaller = context.createMarshaller();
                   marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                   marshaller.marshal(database, new FileWriter("test.xml"));       
    }
}

...I got the result:

...我得到了结果:

<database>
    <records>
        <address>Cologne</address>
        <name>Peter</name>
    </records>
    <records>
        <address>Hamburg</address>
        <name>Mary</name>
    </records>
</database>

But that's not what I was expecting, i.e. all tags for <Data>objects are missing. I am looking for a way to export the data in the following structure, but I don't know how to achieve this:

但这不是我所期望的,即<Data>对象的所有标签都丢失了。我正在寻找一种以以下结构导出数据的方法,但我不知道如何实现:

<database>
    <records>
        <data>
            <address>Cologne</address>
            <name>Peter</name>
        </data>
        <data>
            <address>Hamburg</address>
            <name>Mary</name>
        </data>
    </records>
</database>


One additional question: if I want to deal with the problem withoutusing @XmlElementWrapperand @XmlElementannotations, I can introduce an intermediary class

补充一个问题:如果我想在使用@XmlElementWrapper@XmlElement注解的情况下处理问题,可以引入一个中介类

public class Records
{
    List<Data> data = new ArrayList<Data>();

    public List<Data> getData()                { return data; }
    public void       setData(List<Data> data) { this.data = data; }
}

used by the modified base class

被修改后的基类使用

@XmlRootElement
public class Database
{
    Records records = new Records();

    public Records getRecords()                { return records; }
    public void    setRecords(Records records) { this.records = records; }
}

in a slightly modified Testclass:

在一个稍微修改的Test类中:

...
Database database = new Database();
database.getRecords().getData().add(data1);
database.getRecords().getData().add(data2);
...

The result also is:

结果也是:

<database>
    <records>
        <data>
            <address>Cologne</address>
            <name>Peter</name>
        </data>
        <data>
            <address>Hamburg</address>
            <name>Mary</name>
        </data>
    </records>
</database>

Is this the recommendedway to create a Java class structure according to the XML file structure above?

这是根据上面的 XML 文件结构创建 Java 类结构的推荐方法吗?

回答by bdoughan

On the records property add:

在记录属性上添加:

@XmlElementWrapper(name="records")
@XmlElement(name="data")

For more information on JAXB and collection properties see:

有关 JAXB 和集合属性的更多信息,请参阅:

回答by bdoughan

This is in response to your second question disquised an answer:

这是针对你的第二个问题的回答:

Both approaches will generate the same XML. My recommendation is go with the model that is best for your application. For me that is generally using @XmlElementWrapper/@XmlElement. Since "records" is just there to organize the "data" elements it doesn't really deserve its own class.

这两种方法都将生成相同的 XML。我的建议是使用最适合您的应用程序的模型。对我来说,通常使用@XmlElementWrapper/@XmlElement。由于“记录”只是用于组织“数据”元素,因此它并不真正值得拥有自己的类。

I lead the MOXy JAXBimplementation and we offer an XPath-based mapping extension to go beyond what is capable with @XmlElementWrapper:

我领导MOXy JAXB实现,我们提供了一个基于 XPath 的映射扩展,以超越 @XmlElementWrapper 的能力:

回答by Jér?me Verstrynge

In response to your second question:

针对你的第二个问题:

Is this the recommended way to create a Java class structure
according to the XML file structure above?

Technically speaking, introducing an extra Recordsclass to solve your JAXB issue is unnecessary and redundant work, because JAXB does not need it. The @XmlElementWrapperand @XmlElementnameproperty have been designed to solve your issue.

从技术上讲,引入一个额外的Records类来解决您的 JAXB 问题是不必要和多余的工作,因为 JAXB 不需要它。在 @XmlElementWrapper@XmlElementname财产已被设计为您解决问题。

From your comments to Blaise's answer, I maintain a tutorialwith operational examples explaining how do deal with generic classes such as List, etc.. when unmarshalling.

从您的评论到 Blaise 的回答,我维护了一个带有操作示例的教程,解释了在解组时如何处理泛型类(如 List 等)。