xml 包含混合类容的 JAXB 定义

将xml文件转换为java对象


    This is mixed formatted text value.

1. 定义外层 product

@Getter
@Setter
@XmlRootElement(name = "PRODUCT")
@XmlAccessorType(XmlAccessType.FIELD)
public class Product {

    @XmlAttribute(name = "id")
    private String id;

    @XmlAttribute(name = "name")
    private String name;

    @XmlElementRef(name = "VALUE")
    private Value value;
}

2. 定义 VALUE

@XmlRootElement(name = "VALUE")
@XmlAccessorType(XmlAccessType.FIELD)
public class Value {

    @XmlAttribute(name = "id")
    private String id;

    @XmlAttribute(name = "type")
    private String type;

    @XmlMixed
    @XmlElementRef(name = "TUNIT", type = Tunit.class)
    private List content;
}

3. 定义 UNIT

@Getter
@Setter
@XmlRootElement(name = "TUNIT")
@XmlAccessorType(XmlAccessType.FIELD)
public class Tunit {

    @XmlAttribute(name = "style")
    private String style;

    @XmlValue
    private String content;
}

...元素中有混合内容:纯文本和元素。

因此,在Value类中,您需要定义一个List属性来接收这个混合内容(在您的例子中是Tunit类型的字符串和对象)。为此,您需要使用@XmlMixed@XmlElementRef(定义XML和JavaTunit之间的映射)对其进行注释。另请参见@XmlMixed的API文档中的示例。

对于XML片段This is mixed formatted text value.的XML示例,Value对象中的混合内容列表将接收以下项目:

  • 字符串"This is mixed "
  • Tunit对象
  • 字符串" text value."

结论 最后,Value类将如下

@XmlRootElement(name = "VALUE")
@XmlAccessorType(XmlAccessType.FIELD)
public class Value {

    @XmlAttribute(name = "id")
    private String id;

    @XmlAttribute(name = "type")
    private String type;

    @XmlMixed
    @XmlElementRef(name = "TUNIT", type = Tunit.class)
    private List content;
}

你可能感兴趣的:(JAXB,xml,JAXB)