如何在List <serializable>内容JaxB中添加元素?

时间:2016-05-23 21:17:36

标签: java xml list jaxb serializable

我无法弄清楚如何将元素添加到List<Serializabe> conent,这是我使用JaxB从自动生成的java类中获得的。

例如,我需要在该列表中添加简单字符串,但是当我传递一个字符串

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

它说

  

java.lang.ClassCastException:jaxb.from.xsd.Clan $ Sadrzaj $ Stav无法强制转换为java.lang.String

这是我的代码:

@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;
    }

我的静态类Sadrzaj的XML模式如下所示:

&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>

1 个答案:

答案 0 :(得分:1)

请查看以下相关帖子:JAXB - List?以及相关的Java8文档:Annotation Type XmlMixed

要创建可序列化的JAXBElement,您应该使用生成的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