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

查看:300
本文介绍了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在元素类上注释元素属性

  • 确保注释中元素名称的大小写与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.

更多信息

  • http://blog.bdoughan.com/2011/06/jaxb-and-complex-types-with-simple.html

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

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