[英]How to unmarshal XML file that contains mixed tag (has attributes, and has content value with nested tag) with JAXB?
我需要将 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>
这是产品 class:
@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;
}
这是值 class:
@Getter
@Setter
@XmlRootElement(name = "VALUE")
@XmlAccessorType(XmlAccessType.FIELD)
public class Value {
@XmlAttribute(name = "id")
private String id;
@XmlAttribute(name = "type")
private String type;
@XmlValue
private String content;
@XmlElementRef(name = "TUNIT")
private Tunit tunit;
}
这是 Tunit class:
@Getter
@Setter
@XmlRootElement(name = "TUNIT")
@XmlAccessorType(XmlAccessType.FIELD)
public class Tunit {
@XmlAttribute(name = "style")
private String style;
@XmlValue
private String content;
}
当我为<VALUE>
属性 ID 设置 @XmlAttribute、为<VALUE>
内容设置 @XmlValue 以及为<TUNIT>
设置 @XmlElementRef 时 - 我收到一个错误:
If a class has @XmlElement property, it cannot have @XmlValue property.
是否可以用 JAXB 解组此 xml?
在您的<VALUE...>...</VALUE>
元素中,您有混合内容:纯文本和<TUNIT>
元素。
因此,在您的Value
class 中,您需要定义一个List<Object>
属性来接收此混合内容(在您的情况下是字符串和Tunit
类型的对象。为此,您需要使用@XmlMixed
和@XmlElementRef
(定义 XML <TUNIT>
和 Java Tunit
之间的映射。另请参阅 @XmlMixed 的API 文档中的@XmlMixed
。
对于带有 XML 片段的 XML 示例This is mixed <TUNIT style="style-12">formatted</TUNIT> text value.
Value
object 中的混合内容列表将收到以下项目:
"This is mixed "
Tunit
" text value."
所以最终Value
class 看起来像这样
@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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.