java - 在jaxb中转换xs :string to java. util.UUID

标签 java xsd jaxb uuid

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

最佳答案

如果您从 Java 类开始并使用 JAXB 注释,这更容易做到。但是,要使用模式执行此操作,您必须使用自定义绑定(bind)文件。这是一个例子:

架构:(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>

绑定(bind): (bindings.xjb)包。这些在现实中应该是完全合格的。所以如果 UuidConverter 在包 com.foo.bar 中,那么值应该像 com.foo.bar。 UuidConverter.parsecom.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();
    }
}

遗憾的是,我无法为您指出一个好的引用,因为它确实没有很好的记录。在博客文章中散布了这一切如何运作的点点滴滴。我花了几个小时才第一次完成这项工作。 :-/

关于java - 在jaxb中转换xs :string to java. util.UUID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9565158/

相关文章:

xml - 你如何解析 URN?

xml - xsd 架构引用和类型属性值的命名空间如何别名/绑定(bind)?

java - 如何使用 XSD 和 JSON 或元素/值的 HashMap 作为输入,在 Java 中创建 XML

java - 使用C++的CDC绘制图像的代码可以在Java中使用吗?

java - 依赖注入(inject): Spring and Java

java - 需要可为空的 double 值

java - wsimport 工具正在将生成的客户端代码中的 DataHandler 类型转换为 byte[]

java - 获取在 map 上单击的位置的经纬度 forge 0.5.1 MapView

java - 为什么使用 @Transient 会出现 "org.hibernate.MappingException: In trying to locate getter for property, Class defined both a get and is variant"错误?

java - JAXBElement.getValue() 返回 null