用于base64Binary的XmlAdapter导致String

时间:2014-07-23 06:59:54

标签: xml jaxb xsd adapter xjc

我的XSD文件包含:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
jaxb:extensionBindingPrefixes="xjc"
elementFormDefault="qualified"
targetNamespace="http://example.org/">

<xsd:complexType name="Certificate">
    <xsd:sequence>
        <xsd:element name="certificate" type="xsd:base64Binary">
            <xsd:annotation>
                <xsd:appinfo>
                    <xjc:javaType name="java.security.cert.X509Certificate" adapter="adapters.X509CertificateAdapter" />
                </xsd:appinfo>
            </xsd:annotation>
        </xsd:element>
    </xsd:sequence>
</xsd:complexType>

</xsd:schema>

当我用xjc生成java代码时,它产生了这个:

public class Certificate {

    @XmlElement(required = true, type = String.class)
    @XmlJavaTypeAdapter(X509CertificateAdapter.class)
    @XmlSchemaType(name = "base64Binary")
    protected X509Certificate certificate;

    ....
}

并且适配器工作正常。

我的问题是为什么@XmlElement(required = true, type = String.class)?为什么type = String.class而不是byte[]

2 个答案:

答案 0 :(得分:3)

对于以下内容:

@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(X509CertificateAdapter.class)
@XmlSchemaType(name = "base64Binary")
protected X509Certificate certificate;

有几点需要注意:

  1. type上的@XmlElement设置是多余的,因为X509CertificateAdapter已经指定用于编组&amp;解组它会将X508Certificate转换为String
  2. X509CertificateAdapter转换为String而不是byte[]最有可能出于性能目的,因为转换为byte[]会导致JAXB执行此操作另外转换为String以在XML中正确呈现它。
  3. @XmlSchemaType注释用于确保在生成XML架构时,节点类型显示为base64Binary而不是string

答案 1 :(得分:2)

此类&#34; adapters.X509CertificateAdapter&#34;声明了两种方法:

public X509Certificate unmarshal(String certificateBase64String) throws Exception;
public String marshal(X509Certificate certificate) throws Exception;

第一个声明需要一个String来解组一些X509Certificate。通过这种方式,您可以直接使用X509Certificate。

我希望我已经为您提供了有关您问题的所有答案