gpt4 book ai didi

java - 如何编码(取消)子类中根元素的值

转载 作者:行者123 更新时间:2023-12-02 09:59:43 24 4
gpt4 key购买 nike

我正在使用 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> 的值element,它是子类的根元素。 @XmlMixed似乎并没有促使 JAXB 尝试将任何内容解码到该字段中。

我相信我需要@XmlValue ,但该注释不能用在子类上(除非父类(super class)用 @XmlTransient 注释。)

有人可以建议解决这个问题的方法吗?

限制:

  • 我无法更改 XML 的格式。

  • 我无法摆脱 Model父类(super class)(持久性所需)

  • 我无法修改父类(super class)(来自外部库)

无约束:

  • 如果需要,我可以向父类或子 Java 类添加额外的字段。

  • 如果我可以以任何形式或任何方式将关键字的值获取到类中,我就可以进行任何所需的后处理,以使其处于正确的位置/格式。

  • 它不一定要漂亮。

最佳答案

我在我的代码中尝试过,你可以再试一次!在您的 Maven 中添加此依赖项或下载 jar。

 <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>

那么你不需要改变你的pojo!只需改变您的解码方式即可!我将 xml 存储在文件中,您可以按照您的方式使用,输入流或任何方式。

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);
}

Success

关于java - 如何编码(取消)子类中根元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55727483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com