我需要将 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>
这是产品类别:
@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;
}
这是值类:
@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 类:
@Getter
@Setter
@XmlRootElement(name = "TUNIT")
@XmlAccessorType(XmlAccessType.FIELD)
public class Tunit {
@XmlAttribute(name = "style")
private String style;
@XmlValue
private String content;
}
当我为<VALUE>
设置@XmlAttribute时属性 id,@XmlValue 为 <VALUE>
内容,@XmlElementRef 为 <TUNIT>
- 我收到错误:
If a class has @XmlElement property, it cannot have @XmlValue property.
是否可以使用 JAXB 解码此 xml?
最佳答案
在您的<VALUE ...>...</VALUE>
内你有混合内容的元素:
纯文本和 <TUNIT>
元素。
因此,在您的Value
中类你需要定义一个 List<Object>
属性(property)
接收此混合内容(在您的情况下是字符串和对象
类型 Tunit
。
为此,您需要用 @XmlMixed
对其进行注释。
还有@XmlElementRef
(定义
XML <TUNIT>
之间的映射和 Java Tunit
)。
另请参阅 API documentation of @XmlMixed
中的示例.
对于带有 XML 片段的 XML 示例
This is mixed <TUNIT style="style-12">formatted</TUNIT> text value.
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;
}
关于java - 如何使用 JAXB 解码包含混合标签(具有属性,并且具有嵌套标签的内容值)的 XML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65938694/