解组XML时遇到了UnmarshalException(意外元素),而我刚通过marshaller运行过。我看起来像编组过程生成XML,不能将其解组。
ObjectFactory objectFactory = new ObjectFactory();
EjendomSoegType type = objectFactory.createEjendomSoegType();
EjendomSoegningKriterierType krit = new EjendomSoegningKriterierType();
{
krit.setBy("Skovlunde");
}
type.setEjendomSoegningKriterier(krit);
JAXBElement<EjendomSoegType> soeg = objectFactory.createEjendomSoeg(type);
// create JAXBContext which will be used to update writer
JAXBContext context = JAXBContext.newInstance(EjendomSoegType.class);
// marshall or convert jaxbElement containing element to xml format
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(soeg, writer);
String xml = writer.toString();
System.out.println( xml );
Unmarshaller unmarshaller = context.createUnmarshaller();
StringReader reader = new StringReader(xml);
soeg = (JAXBElement<EjendomSoegType>) unmarshaller.unmarshal(reader);
代码unmarshaller.unmarshal(reader)的最后一行引发以下UnmarshalException:
javax.xml.bind.UnmarshalException: unexpected element (uri:"http://rep.oio.dk/tinglysning.dk/service/message/elektroniskakt/1/", local:"EjendomSoeg"). Expected elements are (none)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:609)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:244)
生成的XML如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns8:EjendomSoeg xmlns:ns2="http://rep.oio.dk/tinglysning.dk/schema/model/1/"
xmlns:ns4="http://rep.oio.dk/cpr.dk/xml/schemas/core/2005/03/18/"
xmlns:ns3="http://rep.oio.dk/kms.dk/xml/schemas/2005/03/11/"
xmlns:ns5="http://rep.oio.dk/bbr.dk/xml/schemas/2005/03/11/"
xmlns:ns6="http://rep.oio.dk/bbr.dk/xml/schemas/2005/12/15/"
xmlns:ns7="http://rep.oio.dk/tinglysning.dk/schema/elektroniskakt/1/"
xmlns:ns8="http://rep.oio.dk/tinglysning.dk/service/message/elektroniskakt/1/">
<ns7:EjendomSoegningKriterier>
<By>Skovlunde</By>
</ns7:EjendomSoegningKriterier>
</ns8:EjendomSoeg>
为什么会引发UnmarshalException?
其他信息:ObjectFactory中的createEjendomSoeg方法具有@XmlElementDecl标记。
/**
* Create an instance of {@link JAXBElement }{@code <}{@link EjendomSoegType }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://rep.oio.dk/tinglysning.dk/service/message/elektroniskakt/1/", name = "EjendomSoeg")
public JAXBElement<EjendomSoegType> createEjendomSoeg(EjendomSoegType value) {
return new JAXBElement<EjendomSoegType>(_EjendomSoeg_QNAME, EjendomSoegType.class, null, value);
}
最佳答案
@XmlElementDecl
上的ObjectFactory
注释未被拾取。要处理ObjectFactory
,您需要在此类或生成的模型的包上创建JAXBContext
。
JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
如果没有与要解组的元素相对应的
@XmlRootElement
或@XmlElementDecl
,则需要使用带有unmarshal
参数的Class
方法。soeg = unmarshaller.unmarshal(new StreamSource(reader), EjendomSoegType.class);