How to unmarshal XML file that contains mixed tag (has attributes, and has content value with nested tag) with JAXB?

Viewed 170

I need to convert xml file to java objects.

<PRODUCT id="10" name="Notebook">
    <VALUE id="30" type="Formatted">This is mixed <TUNIT style="style-12">formatted</TUNIT> text value.</VALUE>
</PRODUCT>

Here is Product class:

@Getter
@Setter
@XmlRootElement(name = "PRODUCT")
@XmlAccessorType(XmlAccessType.FIELD)
public class Product {

    @XmlAttribute(name = "id")
    private String id;

    @XmlAttribute(name = "name")
    private String name;

    @XmlElementRef(name = "VALUE")
    private Value value;
}

Here is Value class:

@Getter
@Setter
@XmlRootElement(name = "VALUE")
@XmlAccessorType(XmlAccessType.FIELD)
public class Value {

    @XmlAttribute(name = "id")
    private String id;

    @XmlAttribute(name = "type")
    private String type;

    @XmlValue
    private String content;

    @XmlElementRef(name = "TUNIT")
    private Tunit tunit;
}

Here is Tunit class:

@Getter
@Setter
@XmlRootElement(name = "TUNIT")
@XmlAccessorType(XmlAccessType.FIELD)
public class Tunit {

    @XmlAttribute(name = "style")
    private String style;

    @XmlValue
    private String content;
}

When I set @XmlAttribute for <VALUE> attribute id, @XmlValue for <VALUE> content, and @XmlElementRef for <TUNIT> - I'm getting an error:

If a class has @XmlElement property, it cannot have @XmlValue property.

Is it possible to unmarshal this xml with JAXB?

1 Answers

Within your <VALUE ...>...</VALUE> element you have mixed content: plain text and a <TUNIT> element.

Therefore, in your Value class you need to define a List<Object> property to receive this mixed content (in your case strings and objects of type Tunit. For this to happen you need to annotate it with @XmlMixed and also with @XmlElementRef (to define the mapping between XML <TUNIT> and Java Tunit). See also the example in the API documentation of @XmlMixed.

For your XML example with the XML fragment
This is mixed <TUNIT style="style-12">formatted</TUNIT> text value.
the mixed content list in the Value object will receive these items:

  • a string "This is mixed "
  • a Tunit object
  • a string " text value."

So finally the Value class will look like this

@XmlRootElement(name = "VALUE")
@XmlAccessorType(XmlAccessType.FIELD)
public class Value {

    @XmlAttribute(name = "id")
    private String id;

    @XmlAttribute(name = "type")
    private String type;

    @XmlMixed
    @XmlElementRef(name = "TUNIT", type = Tunit.class)
    private List<Object> content;
}
Related