JAXB从Anytype访问字符串内容



我有一个预定义的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进程而无需进一步的绑定修改时,我会得到这样的类:

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

to

@XmlAnyElement
@XmlMixed
protected List<Object> any;

对象列表应包含儿童元素的Element和文本String

最新更新