简体   繁体   中英

Marshalling/unmarshalling fields to tag with attributes using JAXB

Let's say I have class Example:

class Example{
  String myField;
}

I want to unmarshal it in this way:

<Example>
  <myField value="someValue" />
</Example>

Is it possible to unmarshal object in such way using JAXB XJC? ( I know about XmlPath in EclipseLink, but can't use it).

You could leverage an XmlAdapter for this use case. In that XmlAdapter you will convert a String to/from an object that has one property mapped to an XML attribute.

XmlAdapter

package forum12914382;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class MyFieldAdapter extends XmlAdapter<MyFieldAdapter.AdaptedMyField, String> {

    @Override
    public String unmarshal(AdaptedMyField v) throws Exception {
        return v.value;
    }

    @Override
    public AdaptedMyField marshal(String v) throws Exception {
        AdaptedMyField amf = new AdaptedMyField();
        amf.value = v;
        return amf;
    }

    public static class AdaptedMyField {

        @XmlAttribute
        public String value;

    }

}

Example

package forum12914382;

import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement(name="Example")
@XmlAccessorType(XmlAccessType.FIELD)
class Example{

    @XmlJavaTypeAdapter(MyFieldAdapter.class)
    String myField;

}

Demo

package forum12914382;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Example.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum12914382/input.xml");
        Example example = (Example) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(example, System.out);
    }

}

input.xml/Output

<Example>
  <myField value="someValue" />
</Example>

Related Example

是的,手动添加@XmlAttribute -Annotation或从XSD生成类。

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