JAXB:如何在包装类型中获得价值?

cac*_*kle 3 java xml jaxb

@XmlRootElement(name = "toplist")
class toplist {

    private String description;

    private List<Item> items= new ArrayList<Item>();

    @XmlElement(name = "description")
    public String getDescription() {...}
    public String setDescription() {...}

    @XmlElement(name = "item")
    @XmlElementWrapper(name = "items")
    public List<ChartResultItem> getToplistEntries() {...}
}

class Item {
    private String attr1;
    private String attr2;
    private String attr3;

    // getter and setter with
    //     @XmlAttribute(name = "atter1"), @XmlAttribute(name = "atter2") and etc
}
Run Code Online (Sandbox Code Playgroud)

和xml

<?xml version="1.0" encoding="UTF-8"?>
<toplist>
    <description>This is description.</description>
    <items>
        <item attr1="" attr2="" attr3="">value1</item>
        <item attr1="" attr2="" attr3="">value2</item>
        <item attr1="" attr2="" attr3="">value3</item>
        ...
    </items>
</toplist>
Run Code Online (Sandbox Code Playgroud)

如何在Item类中获取value1,value2,value3等(通过jaxb)?

Jör*_*ann 5

您可能正在寻找XmlValue注释.


alp*_*ian 5

Jom的答案是正确的(+1).这是一个进一步解释的例子:

@XmlAccessorType(XmlAccessType.FIELD)
public class Item {
    @XmlValue
    protected String value;

    @XmlAttribute
    protected String attr1;

    @XmlAttribute
    protected String attr2;

    @XmlAttribute
    protected String attr3;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果要对字段进行注释,则还应使用类级别注释:@XmlAcessorType(XmlAcessType.FIELD).这将解决您所看到的问题. (3认同)