我有一个预定义的 xsd 架构(不幸的是我无法修改),我喜欢通过 JAXB 为其生成相应的 JAVA 类。目前我正在努力处理定义如下的复杂类型。
<xsd:complexType name="AttributeType">
<xsd:complexContent>
<xsd:extension base="xsd:anyType">
<xsd:attribute name="id" type="xsd:anyURI" use="required"/>
<xsd:anyAttribute processContents="lax"/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
提供的 XML 示例允许直接字符串内容,如下所示:
<attribute id="myValue">201</attribute>
以及像这样的嵌入式 xml:
<attribute id="address">
<example:Address xmlns:example="http://example.com/ns">
<Street>100 Nowhere Street</Street>
<City>Fancy</City>
<State>DC</State>
<Zip>99999</Zip>
</example:Address>
</attribute>
当运行 xjc 进程而不进行进一步的绑定(bind)修改时,我得到一个像这样的类:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AttributeType", propOrder = {
"any"
})
public class AttributeType {
@XmlAnyElement
protected List<Element> any;
@XmlAttribute(name = "id", required = true)
@XmlSchemaType(name = "anyURI")
protected String id;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
// getter setter omitted
}
问题是,我无法获取第一个示例的字符串内容。这可能引用XSD anytype and JAXB ,但实际上我不知道如何在不修改 XSD 的情况下实现这一目标。那么如何获取字符串内容呢?顺便提一句。我正在使用 Maven cxf-codegen-plugin 来生成源代码。
最佳答案
我认为问题来自于生成的映射查找子元素,而不是文本。
如果您可以修改 XSD,解决方案是:
<xsd:complexType name="AttributeType">
<xsd:complexContent mixed="true">
<xsd:extension base="xsd:anyType">
<xsd:attribute name="id" type="xsd:anyURI" use="required"/>
<xsd:anyAttribute processContents="lax"/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
但是既然你不能...
如果您有能力修改源代码,请更改:
@XmlAnyElement
protected List<Element> any;
至
@XmlAnyElement
@XmlMixed
protected List<Object> any;
对象列表应包含子元素的 Element
和文本的 String
。
关于java - JAXB从anyType访问字符串内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38093995/