Java Code to XML/XSD without using Annotation

后端 未结 3 1268
一个人的身影
一个人的身影 2020-12-30 07:40

I need to marshall and unmarshall a Java class to XML. The class in not owned by me, that I cannot add anotations so that I can use JAXB.

Is there a good way to conv

3条回答
  •  醉酒成梦
    2020-12-30 07:55

    You could write a custom XmlAdapter and annotate fields of the constrained type with a XmlJavaTypeAdapter annotation. The basics would be something like this:

    public enum CannotBeAnnotated { value1, value2; }
    @XmlRootElement(name="client")
    public class ClientClass {
        @XmlJavaTypeAdapter(Bridge.class)
        public CannotBeAnnotated;
    }
    @XmlRootElement(name="representation")
    public class XmlType {
        @XmlValue
        public String value;
    }
    public class Bridge extends XmlAdapter{
        public XmlType marshal(CannotBeAnnotated c) {
            XmlType x=new XmlType(); 
            x.value=c.name();
            return x;
        }
        public CannotBeAnnotated unmarshall(XmlType x) {
            return CannotBeAnnotated.valueOf(x.value);
        }
    }
    

    Of course for enums this would not be useful as JAXB knows how to deal with them. I just picked an enum for simplicity so you can see the idea:

    1. Design an XML representation that you do control
    2. Write an adapter converting that Java type into the desired type
    3. Annotate "client" code referencing the adapter for the desired type
    4. Profit.

提交回复
热议问题