0

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?

1
  • While editing your question I noticed that your XML is invalid because you have an opening tag named comboBox, but your closing tag is named combobox. Commented Jan 7, 2018 at 21:20

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I tried this before, but didn't work before because I overlooked one of the xmlElements like comboBox etc but after you answered I tried again and found where I committed the mistake, I will accept the answer, Thanks again
0

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)

1 Comment

I didn't get it Can you post with some example code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.