如何使用JAXB通过XSD模式限制在我的Java代码创建UUID

问题描述 投票:0回答:1

我要去使用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()or任何其他方式传递XSD

java xml xsd jaxb
1个回答
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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.