JAXB 编组具有相同名称的元素的变量列表 [英] JAXB Marshalling a variable list of elements with the same name

查看:32
本文介绍了JAXB 编组具有相同名称的元素的变量列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据标题,我有一个需要解组的 XML 文件:

As per the title, I have an XML file I need to unmarshal:

<?xml version="1.0"?>
<root>
    <wrap>
        <Element>something1</Element>
        <Element>something2</Element>
        <Element>something3</Element>
    </wrap>
</root>

wrap"只是一个包装器,但是元素"的数量是不同的.

"wrap" is simply a wrapper, but the count of "element" varies.

我有两个类来促进 JAXB 的对象:

I have two classes to facilitate objects for JAXB:

包装类:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "root")
public class Wrap {
    @XmlElementWrapper(name = "wrap")
    @XmlElement(name = "Element")
    private List<Element> elementList = new ArrayList<>();

    public Wrap() {}

    public Wrap(List<Element> list) {
        this.elementList = list;
    }

    public void addElement(Element element) {
        this.elementList.add(element);
    }

    public List<Element> getWrap() {
        return this.elementList;
    }

    public void setWrap(List<Element> wrap) {
        this.elementList = wrap;
    }
}

元素类:

@XmlRootElement(name = "Element")
public class Element {

    private String Element;

    public Element() {}

    public Element(String element) {
        this.Element = element;
    }

    public String getElement() {
        return Element;
    }

    public void setElement(String element) {
        this.Element = element;
    }
}

尝试解组 XML 可以顺利完成,但是,元素值并未与元素对象一起存储.相反,toString 为每个对象返回 null.

Attempting to unmarshal the XML completes without error, however, the element values are not stored with the element objects. Instead toString returns null for each of the objects.

我确实用一些数据填充了对象并将它们编组到一个文件中(如下所示).这种格式当然是不正确的,应该与上面的 XML 匹配.

I did populate the objects with some data and marshal them to a file (shown below). This format, of course, is incorrect and should match the XML above.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <wrap>
        <Element>
            <element>entry1</element>
        </Element>
        <Element>
            <element>entry2</element>
        </Element>
        <Element>
            <element>entry3</element>
        </Element>
    </wrap>
</root>

我已经研究了一段时间,假设我的注释不正确,但也许是别的东西......

I've researched this for awhile now with the assumptions my annotations are incorrect, but perhaps it's something else...

推荐答案

您需要做到以下几点:

  • 使用 @XmlValue 注释 Element 类上的 element 属性.
  • 确保注释中元素名称的大小写与 XML 文档中的名称匹配.
  • annotate the element property on the Element class with @XmlValue.
  • make sure the case of the element names in the annotations matches the names in the XML document.

了解更多信息

这篇关于JAXB 编组具有相同名称的元素的变量列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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