简体   繁体   中英

XML Mapping to Java Object

I have a Xml Like this

<entry>
  <comboBox>
    <name>xxx</name>
    <details>sdfd</details>
  </comboBox>
</entry>

In the other entry I have XML like this

<entry>
  <numberField>
    <name>xxx</name>
    <details>sdfd</details>
  </numberField>
</entry>

I want to map both comboBox and numberField to the same class in Java called Field

How do I annotate Java Fields in Entry Class?

In your Entry class you need to annotate the Java field with @XmlElements and list the individual element names there. Like this:

@XmlAccessorType(XmlAccessType.FIELD)
public class Entry {

    @XmlElements({
        @XmlElement(name = "comboBox", type = Field.class),
        @XmlElement(name = "numberField", type = Field.class)
    })
    private Field field;
}

I have added type = Field.class in the annotation above only for clarity. In your case you can omit it. Then JAXB will pick up Field from the property type decaration , which has the same desired effect.

The Field class can be straight-forward like this:

@XmlAccessorType(XmlAccessType.FIELD)
public class Field {

    @XmlElement
    private String name;

    @XmlElement
    private String details;
}

I think you should make two sub classes of an object which has the common annoted fields. Each sub class just has to define jaxb @XmlRootElement (number field or combobox)

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