简体   繁体   中英

JAXB Attribute as Element Value

I have XML that is defined as

<ROOT>
    <CHILD1 VALUE=""/>
    <CHILD2 VALUE=""/>
</ROOT>

Is there any way that I can pull out the VALUE attribute as the value of the element instead of treating CHILD1 as a ComplexType with a VALUE attribute so that it would fit this pojo?

@XmlRootElement(name="ROOT")
public class Root {

    @XmlElement(name="CHILD1")
    private String child1;

    @XmlElement(name="CHILD2")
    private String child2;
}

Well there are some cutomiziation binding feature in JAXB : https://docs.oracle.com/javase/tutorial/jaxb/intro/custom.html But this will be rather complicated for something not so important I guess.

If your Java Pojos are not generated you could simply add methods to have direct access to the subfield eg Root.getChild1String() which would call Root.getChild1().getValue()

Or you could change the xml schema.

I ended up writing an adapter to transform the property for deserialization.

@XmlElement(name = "CHILD1")
@XmlJavaTypeAdapter(ValueAdapter.class)
private String child1;

public class ValueAdapter extends XmlAdapter<Object, String> {
    private static String VALUE = "VALUE";
    @Override
    public String unmarshal(Object e) throws Exception {
        if (e instanceof ElementNSImpl && ((ElementNSImpl)e).hasAttribute(VALUE)) {
            return ((ElementNSImpl)e).getAttribute(VALUE);
        }
        return null;
    }

    @Override
    public Object marshal(String s) throws Exception {
        return null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM