我无法弄清楚如何将元素添加到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模式如下所示:
<complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice>
* <element name="Stav" maxOccurs="unbounded">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Redni_broj" type="{http://www.w3.org/2001/XMLSchema}long"/>
* <element name="Tekst" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="Tekst" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded"/>
* </choice>
* </restriction>
* </complexContent>
* </complexType>
答案 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