java - JAXB 解码子属性而不创建子类

标签 java xml jaxb unmarshalling

我想解码一个(简化的)XML 结构,如下所示:

<parent>
    <a>AValue</a>
    <b>BValue</b>
    <c someAttribute = "true">CValue</c>
</parent>

我知道如何通过声明类 C 来做到这一点:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "c", propOrder = {
        "someAttribute"
    })
public class C{
    @XmlValue
    private String c;
    @XmlAttribute ( name="someAttribute")
    private boolean someAttribute;
    //getters and setters
}

并将其作为父类中的成员,如下所示:

public class Parent{
   private String a;
   private String b;
   private C c;
   //getters and setters for c,b,a
}

这可以工作,我可以通过 parent.getC().getC(); 访问 C 的值 我的问题是如何实现我不必创建类C并获取属性 C 作为 parent 的成员,无需使用新成员和其他 getter 和 setter 编辑 parent Pojo。 我已经尝试通过监听器执行此操作并搜索类似的结构,但我没有留下任何想法。

最佳答案

我终于知道如何实现这一目标了。 必须使用 @XmlJavaTypeAdapter 注解并将 C 类标记为 @XmlRootElement 以及 @XmlAccessorType(XmlAccessType.FIELD)。 此外,需要在使用 @XmlJavaTypeAdapter 注释的 String 成员的 getter 上使用 @XmlTransient

完整解决方案:

C类:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class C{
    @XmlValue
    private String c;

    @XmlAttribute
    private boolean someAttribute;
    //getters and setters for both

类适配器:

public class Adapter extends XmlAdapter<C, String> {

    public String unmarshal(C pC) throws Exception {
        //some possible handling with the attribute over pC.getSomeAttribute();
        return pC.getC();
    }

    public C marshal(String pC) throws Exception {
       C c = new C();
       c.setC(pC)
       //some possible handling to set the attribute to c
       return c;
    }

类(class)家长:

public class Parent{
   private String a;
   private String b;
   @XmlJavaTypeAdapter(Adapter.class)
   private String c;

   @XmlTransient
    public String getC() {
        return c;
    }
   //getters and setters for b,a and setter for C
}

关于java - JAXB 解码子属性而不创建子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54071956/

相关文章:

java - Jersey/Jaxb 返回字符串列表而不是整数

javax.xml.bind.JAXBException : Class *** nor any of its super class is known to this context

java - LibGDX - Stage.setViewport(new Viewport()) 黑屏

c# - 使用 C# 反序列化 XML 文件,其中元素具有属性和值

html - 输入元素后标签的 XPath?

java - JAXB un/marshalling : Is there a difference between using arrays and lists?

java - 获取 ImageView 可绘制 ID 并使用 AsyncTask 更改它

java - thymeleaf 。如何根据 boolean 参数隐藏元素?

java - 看似公共(public)功能的不可访问功能

c# - 从 C# 生成 Excel - 如何制作对角线边框?