Convert xs: string to java.util.UUID in jaxb

In jaxb, how do you convert a string to xsd in java.util.UUID? Is there a built-in data type converter or do I need to create my own custom converter?

+6
source share
2 answers

This is easier if you start with Java classes and use JAXB annotations. However, to do this using a schema, you must use your own binding file. Here is an example:

Schematic: (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, which should be fully qualified in reality. Therefore, if the UuidConverter where UuidConverter in the package 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(); } } 

Unfortunately, I can’t direct you to a good link, because it is really not documented. There are bits and pieces of how it all works on blogs. It took me several hours to do this work for the first time .: - /

+10
source

Create a simple converter yourself:

 UUID.fromString(String uuid); 

http://docs.oracle.com/javase/6/docs/api/java/util/UUID.html

0
source

Source: https://habr.com/ru/post/909987/


All Articles