Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I specify the adapter(s) which JAXB uses for marshaling/unmarshaling data?
    text
    copied!<p>Is there a way to specify the Adapter which JAXB uses for marshaling/unmarshaling objects in my XML schema?</p> <p>For example, if I want to parse the following as an integer:</p> <pre><code>&lt;SpecialValue&gt;0x1234&lt;/SpecialValue&gt; </code></pre> <p>I can use the following in my schema:</p> <pre><code>&lt;xs:simpleType name="HexInt"&gt; &lt;xs:annotation&gt; &lt;xs:appinfo&gt; &lt;jaxb:javaType name="int" parseMethod="Integer.decode" /&gt; &lt;/xs:appinfo&gt; &lt;/xs:annotation&gt; &lt;xs:restriction base="xs:string"&gt; &lt;xs:pattern value="0x[0-9a-fA-F]+" /&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; &lt;xs:element name="SpecialValue" type="HexInt" /&gt; </code></pre> <p>When I run the schema through the XJC tool, the String "0x1234" should be decoded using Integer.decode() as the Integer with value 0x1234, or 4660 in decimal. The Adapter class that is generated reflects this properly:</p> <pre><code>public Integer unmarshal(String value) { return (Integer.decode(value)); } </code></pre> <p>However, when I want to marshal the value back to an XML element (which is a String literal), the Adapter class does the following:</p> <pre><code>public String marshal(Integer value) { if (value == null) { return null; } return value.toString(); } </code></pre> <p>In this case, the String value of the integer 0x1234 (4660 in decimal) is "4660", which does not adhere to my schema (because it has no "0x" prefix).</p> <p>How can I tell the Adapter that I want the integer 0x1234 to be marshalled as the "0x1234" String literal? I would be like to be able to do this within the schema so that I can just generate new Java classes without having to modify the output. Is this possible?</p> <p><strong>Edit:</strong> Based on the accepted answer, here is what I did to get this working:</p> <p>I wrote a method in a class com.example.Parse called toHexString():</p> <pre><code>public static String toHexString(int value) { return ("0x" + Integer.toHexString(value)); } </code></pre> <p>Then I pointed my schema to that method for printing:</p> <pre><code>&lt;xs:simpleType name="HexInt"&gt; &lt;xs:annotation&gt; &lt;xs:appinfo&gt; &lt;jaxb:javaType name="int" parseMethod="Integer.decode" printMethod="com.example.Parse.toHexString" /&gt; &lt;/xs:appinfo&gt; &lt;/xs:annotation&gt; &lt;xs:restriction base="xs:string"&gt; &lt;xs:pattern value="0x[0-9a-fA-F]+" /&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload