本文介绍了在xaxb中将xs:string转换为java.util.UUID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jaxb中,如何将xsd中的字符串转换为java.util.UUID?是否有内置数据类型转换器或者我是否必须创建自己的自定义转换器?

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?

推荐答案

这是如果从Java类开始并使用JAXB注释,那么会更容易。但是,要使用模式执行此操作,必须使用自定义绑定文件。以下是一个示例:

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:

架构:(example.xsd)

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.xjb)(注意,为简洁起见, printMethod parseMethod 我假设 UuidConverter 类在默认包中。这些应该是完全的实际上是合格的。所以,如果 UuidConverter 在包 com.foo.bar 中,那么值应该像 com.foo.bar.UuidConverter.parse com.foo.bar.UuidConverter.print

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:

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. :-/

这篇关于在xaxb中将xs:string转换为java.util.UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 04:28