In jaxb, how do you convert a string in xsd to java.util.UUID? Is there a built-in data type converter or do I have to create my own custom converter?
This is much easier to do if you start with Java classes and use JAXB annotations. However, to do this using schema you must use a custom bindings file. Here is an example:
Schema: (example.xsd)
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.com"
xmlns="http://www.example.com"
elementFormDefault="qualified">
<xs:simpleType name="uuid-type">
<xs:restriction base="xs:string">
<xs:pattern value=".*"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="example-type">
<xs:all>
<xs:element name="uuid" type="uuid-type"/>
</xs:all>
</xs:complexType>
<xs:element name="example" type="example-type"/>
</xs:schema>
Bindings: (bindings.xjb) (Note that for brevity in printMethod
and parseMethod
I assumed that the UuidConverter
class was in the default package. These should be fully qualified in reality. So if UuidConverter
where in package com.foo.bar
then the values should be like com.foo.bar.UuidConverter.parse
and com.foo.bar.UuidConverter.print
<!-- Modify the schema location to be a path or url -->
<jxb:bindings version="1.0"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
node="/xs:schema"
schemaLocation="example.xsd">
<!-- Modify this XPATH to suit your needs! -->
<jxb:bindings node="//xs:simpleType[@name='uuid-type']">
<jxb:javaType name=" java.util.UUID"
parseMethod="UuidConverter.parse"
printMethod="UuidConverter.print"/>
</jxb:bindings>
</jxb:bindings>
UuidConverter.java:
import java.util.UUID;
public class UuidConverter {
public static UUID parse(String xmlValue) {
return UUID.fromString(xmlValue);
}
public static String print(UUID value) {
return value.toString();
}
}
Sadly I can't point you to a good reference because its really not documented well. There are bits and pieces of how it all works spread out in blog posts. Took me a few hours to make this work the first time. :-/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With