4

I cant figure it out how to add an element to List<Serializabe> conent, which i got from auto generated java classes using JaxB.

For example, i need to add simple string in that list, but when i pass a string

sadrzaj.getContent().add("some string");

it says that

java.lang.ClassCastException: jaxb.from.xsd.Clan$Sadrzaj$Stav cannot be cast to java.lang.String

Here is my code:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "content"
})
public static class Sadrzaj {

@XmlElementRefs({
@XmlElementRef(name = "Tekst", namespace = "http://www.parlament.gov.rs/clan", type = JAXBElement.class),
@XmlElementRef(name = "Stav", namespace = "http://www.parlament.gov.rs/clan", type = JAXBElement.class)
    })
    @XmlMixed
    protected List<Serializable> content;

    public List<Serializable> getContent() {
        if (content == null) {
            content = new ArrayList<Serializable>();
        }
        return this.content;
    }

My XML schema for static class Sadrzaj looks like this:

&lt;complexType>
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;choice>
 *         &lt;element name="Stav" maxOccurs="unbounded">
 *           &lt;complexType>
 *             &lt;complexContent>
 *               &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 &lt;sequence>
 *                   &lt;element name="Redni_broj" type="{http://www.w3.org/2001/XMLSchema}long"/>
 *                   &lt;element name="Tekst" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *                 &lt;/sequence>
 *               &lt;/restriction>
 *             &lt;/complexContent>
 *           &lt;/complexType>
 *         &lt;/element>
 *         &lt;element name="Tekst" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded"/>
 *       &lt;/choice>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
Martel
  • 49
  • 6

1 Answers1

4

Please have a look to this related post: JAXB - List? and the related Java8 documentation: Annotation Type XmlMixed

To create a serializable JAXBElement, you should use the generated ObjectFactory:

 LetterBody lb = ObjectFactory.createLetterBody();
 JAXBElement<LetterBody> lbe = ObjectFactory.createLetterBody(lb);
 List gcl = lb.getContent();  //add mixed content to general content property.
 gcl.add("Dear Mr.");  // add text information item as a String.

 // add child element information item
 gcl.add(ObjectFactory.createLetterBodyName("Robert Smith"));
 gcl.add("Your order of "); // add text information item as a String

 // add children element information items
 gcl.add(ObjectFactory.
                      createLetterBodyQuantity(new BigInteger("1")));
 gcl.add(ObjectFactory.createLetterBodyProductName("Baby Monitor"));
 gcl.add("shipped from our warehouse");  // add text information item
Erik Wolf
  • 144
  • 1
  • 12