我正在使用JAXB将一个复杂的对象从XML解组为Java。 XML中有问题的部分如下:
<product>
<!-- SNIP -->
<keywords>
<keyword optionalAttribute="attrValue">Value</keyword>
<keyword>Another value</keyword>
</keywords>
</product>
我有一个Java类用于父对象和复杂属性,包括关键字,带有javax.xml.bind.annotation.*
注释。
@XmlRootElement(name = "product")
@XmlAccessorType(XmlAccessType.NONE)
public class Product extends Model {
// SNIP
@XmlElementWrapper(name = "keywords")
@XmlElement(name = "keyword")
public List<ProductKeyword> keywords;
}
@XmlRootElement(name = "keyword")
@XmlAccessorType(XmlAccessType.NONE)
public class ProductKeyword extends Model {
@XmlAttribute(name = "optionalAttribute")
public String optionalAttribute;
@XmlMixed
public String keyword;
}
ProductKeyword.keyword
字段需要保存<keyword>
元素的值,@XmlMixed
元素是子类的根元素。 @XmlValue
似乎并没有诱使JAXB尝试解散任何进入该领域的事情。
我相信我需要@XmlTransient
,但该注释不能用于子类(除非可能使用Model
注释超类)。
任何人都可以建议解决这个问题吗?
约束:
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.moxy</artifactId>
<version>2.5.0-RC1</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.persistence</groupId>
<artifactId>commonj.sdo</artifactId>
</exclusion>
</exclusions>
</dependency>
超类(持久性所需)非约束:
我在我的代码中试图,你可以再试一次!在Maven中添加了这个依赖项或者下载了jar。
public static void main(String[] args) throws JAXBException, IOException {
JAXBContext context = JAXBContextFactory.createContext(new Class[]{Product.class}, new HashMap());
Unmarshaller unmarshaller = context.createUnmarshaller();
InputStream is = new ClassPathResource("stand.xml").getInputStream();
Product product= (Product) unmarshaller.unmarshal(is);
System.out.println(product);
}
然后你不需要改变你的pojo!只是改变你解散的方式!我将xml存储在文件中,你可以使用你的方式,输入流或任何。
qazxswpoi