我得到了 xsd我从中生成了 JaxB 类(例如 ApplicationCustomType)。某些类具有 xs:any 作为元素。我可以向这些字段添加内容(例如 xs:any)。编码工作良好。
但是当我尝试解码它时
FullContent contentType = XmlObjectHelper.getXmlTypeFromString(contentType, FullContent.class);
JaxB 类并未使用每个 xs:any 中的字段进行填充。所有其他字段均按应填写,但 xs:any 的绑定(bind)似乎不起作用。
我读到serializing-with-jaxb答案看起来很相似,我想我没有忘记什么。 我还尝试添加 lax = true但它再次没有解码我的 xml。
我做错了什么或者我忘记了什么?
public class ApplicationCustomType {
@XmlAnyElement
protected List<Element> any;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
示例 xs:any 元素。
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "addressAttachment", propOrder = {
"locale",
"ourUserId"
})
public class AddressAttachment {
@XmlElement(required = false)
protected String locale;
@XmlElement(required = false)
protected String ourUserId;
}
ObjectFactory.java
@XmlElementDecl(namespace = "http://***/xsd/addressAttachment/v1", name = "information")
public JAXBElement<AddressAttachment> createAddressAttachment(AddressAttachment value) {
return new JAXBElement<AddressAttachment>(_AddressAttachment_QNAME, AddressAttachment.class, null, value);
}
我收到的 xml:
<content>
<applicationCustom>
<addressAttachment>
<locale>CH.de</locale>
<ourUserId>264646337383839</ourUserId>
</addressAttachment>
</applicationCustom>
</content>
解决方案:
我们在列表顶部而不是类上重试了 (lax = true)。
public class ApplicationCustomType {
@XmlAnyElement(lax = true)
protected List<Element> any;
如果您使用<Element>
或<Object>
不影响结果。使用时Element
实际上,您不必向编码器提供该类。但在这两种情况下您都需要添加 @XmlElementDecl
对于每个 XMLRoot
您要添加到 xs:any 列表中的每个对象的对象工厂中的类。
最佳答案
尝试像这样使用它:
@XmlAnyElement
protected List<Object> any;
看看里面有什么!
解释在这里:https://dzone.com/articles/jaxbs-xmlanyelementlaxtrue
您还应该向解码器提供已知的类(AddressAttachment.class...),否则它无法找出 xml 中的内容,对吗?
您的示例中未显示,但应如下所示:
JAXBContext.newInstance(FullContent.class,AddressAttachment.class ...);
对于 Any,根对象本身没有引用。
与 Jaxb 一起度过愉快的时光
关于java - 为什么xs :any not autobind with jaxb class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32372217/