问题
I've an XSD file containing this:
<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>
and when I generate java code with xjc, it produces this:
public class Certificate {
@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(X509CertificateAdapter.class)
@XmlSchemaType(name = "base64Binary")
protected X509Certificate certificate;
....
}
and the adapter works fine.
My question is why @XmlElement(required = true, type = String.class)
? Why type = String.class
and not byte[]
?
回答1:
For the following:
@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(X509CertificateAdapter.class)
@XmlSchemaType(name = "base64Binary")
protected X509Certificate certificate;
There are a few things to note:
- The
type
setting on@XmlElement
is redundant since theX509CertificateAdapter
already specifies that for the purposes of marshalling & unmarshalling it is going to convertX508Certificate
to/from aString
. - The
X509CertificateAdapter
converts to/from aString
instead of abyte[]
most likely for the purposes of performance, as a conversion to abyte[]
would cause JAXB to do an additional conversion toString
to render it correctly in the XML. - The
@XmlSchemaType
annotation is used to ensure that when an XML Schema is generated that the node type shows up asbase64Binary
and notstring
.
回答2:
This class "adapters.X509CertificateAdapter" declares two methods:
public X509Certificate unmarshal(String certificateBase64String) throws Exception;
public String marshal(X509Certificate certificate) throws Exception;
The first declaration needs of a String to unmarshal some X509Certificate. In this way you can use directly a X509Certificate.
I hope I've given you all the answers about your question
来源:https://stackoverflow.com/questions/24903790/xmladapter-for-base64binary-results-in-string