如何(un)编组子类中根元素的值

问题描述 投票:0回答:1

我正在使用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注释超类)。

任何人都可以建议解决这个问题吗?

约束:

  • 我无法改变XML的格式。
  • 我无法摆脱 <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> 超类(持久性所需)
  • 我无法修改超类(来自外部库)

非约束:

  • 如果需要,我可以向父或子Java类添加额外的字段。
  • 如果我可以以任何形式或任何方式将关键字的值放入类中,我可以做任何我需要的后处理以获得正确的位置/格式。
  • 它不一定非常漂亮。
java xml jaxb
1个回答
1
投票

我在我的代码中试图,你可以再试一次!在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存储在文件中,你可以使用你的方式,输入流或任何。

Success

qazxswpoi

© www.soinside.com 2019 - 2024. All rights reserved.