如何使用JAXB在Java代码中创建UUID来传递XSD模式限制

时间:2019-02-03 10:49:38

标签: java xml xsd jaxb

我要创建ID在我的Java代码中使用域UUID。我需要从我的Book类创建 xml 并根据XSD下面的内容对其进行验证。

我的XSD看起来像这样

<xsd:complexType name="Book" >
    <xsd:sequence>
        <xsd:element name="Publisher" type="ns:PublisherType"/>
        <xsd:element name="MessageId" type="ns:GUID"/>
        <xsd:element name="Author" type="xsd:string"/>
        <xsd:element name="Title" type="xsd:string"/>
        <xsd:any processContents="lax" minOccurs="0" maxOccurs="unbounded"
                 namespace="##other"/>
    </xsd:sequence>
</xsd:complexType>

<xsd:simpleType name="GUID">
    <xsd:restriction base="xsd:string">
        <xsd:pattern value="[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}"/>
    </xsd:restriction>
</xsd:simpleType>

我的Java类如下

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
@XmlType(name="Book", propOrder = {"publisher", "messageId", "author", "title"
})
@Getter
@Setter
public class Book {

    private Publisher publisher;
    private GUID messageId;    
    private String author;  
    private String title;
}

我应该如何实现我的GUID类以返回UUID.randomUUID()或其他任何方式来传递XSD

1 个答案:

答案 0 :(得分:1)

看看this example,基本上,您必须用@XmlValue注释返回xml值的方法

public class GUID {

    private final UUID uuid;

    public GUID() {
        this.uuid = UUID.randomUUID();
    }

    @XmlValue
    public String getValue(){
        return uuid.toString();
    }
}