【问题标题】:JAXB unmarshal child attributes without creation of child classJAXB 解组子属性而不创建子类
【发布时间】:2019-01-07 09:50:42
【问题描述】:

我想像这样解组一个(简化的)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 并获得Cattributeattribute 作为parent 的成员,而无需编辑parent Pojo 与新成员和其他 getter 和 setter。 我已经尝试通过 Listeners 执行此操作并搜索了类似的结构,但我没有任何想法。

【问题讨论】:

    标签: java xml jaxb unmarshalling


    【解决方案1】:

    我终于想出了如何实现这一点。 必须使用@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;
        }
    

    班级家长:

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-28
      • 1970-01-01
      • 2011-07-03
      • 2023-03-14
      • 2021-09-20
      • 2011-08-19
      • 2015-10-02
      • 2010-10-11
      • 1970-01-01
      相关资源
      最近更新 更多