将xml文件转换为java对象
<PRODUCT id="10" name="Notebook">
<VALUE id="30" type="Formatted">This is mixed <TUNIT style="style-12">formatted</TUNIT> text value.</VALUE>
</PRODUCT>
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<Object> 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 ...>...</VALUE>
元素中有混合内容:纯文本和<TUNIT>
元素。
因此,在Value
类中,您需要定义一个List<Object>
属性来接收这个混合内容(在您的例子中是Tunit
类型的字符串和对象)。为此,您需要使用@XmlMixed
和@XmlElementRef
(定义XML<TUNIT>
和JavaTunit
之间的映射)对其进行注释。另请参见@XmlMixed
的API文档中的示例。
对于XML片段This is mixed <TUNIT style="style-12">formatted</TUNIT> 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<Object> content;
}