java - 让 JAXB 在编码到 XML 时强制执行 XSD 限制

标签 java xml xsd jaxb

我有一个 XML 架构,它将电影分级限制为 1 到 10 之间的值(含 1 和 10)。但是,JAXB 绑定(bind)允许我保存评分为 11 的电影。如果某个值不符合 XSD 中的限制,有没有办法让 JAXB 在编码期间抛出异常?

这是 XSD:

<?xml version="1.0"?>
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

    <xsd:simpleType name="RatingType">
        <xsd:annotation>
            <xsd:documentation xml:lang="en">A rating between 1 and 10 inclusive</xsd:documentation>
        </xsd:annotation>
        <xsd:restriction base="xsd:float">
            <xsd:minInclusive value="1.0" />
            <xsd:maxInclusive value="10.0" />
        </xsd:restriction>
    </xsd:simpleType>

    <xsd:complexType name="MovieRatingType">
        <xsd:sequence>
            <xsd:element name="Title" type="xsd:string" minOccurs="1" maxOccurs="1" />
            <xsd:element name="Rating" type="RatingType" minOccurs="1" maxOccurs="1" />
        </xsd:sequence>
    </xsd:complexType>

    <xsd:complexType name="MoviesListType">
        <xsd:sequence>
            <xsd:element name="Movie" type="MovieRatingType" maxOccurs="unbounded" />
        </xsd:sequence>
    </xsd:complexType>

    <xsd:element name="Movies" type="MoviesListType" />

</xsd:schema>

这是代码:

import generated.MovieRatingType;
import generated.MoviesListType;
import generated.ObjectFactory;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class RestrictionTest {

    public static void main(String[] args) {

        ObjectFactory factory = new ObjectFactory();

        MovieRatingType movie = new MovieRatingType();
        movie.setTitle("Terminator");
        movie.setRating(11.3f); //<--- rating set to higher than the allowed value

        MoviesListType movieList = factory.createMoviesListType();
        movieList.getMovie().add(movie);

        JAXBElement<MoviesListType> moviesListJAXB = factory.createMovies(movieList);

        try {

            File file = new File("C:\\Users\\perezsmithf\\Desktop\\dev\\java\\scratch\\src\\output.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(MoviesListType.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            jaxbMarshaller.marshal(moviesListJAXB, file); //<--- at this point it should throw an exception because the rating is too high
            jaxbMarshaller.marshal(moviesListJAXB, System.out);

        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

最佳答案

您需要注册一个ValidationEventHandler,它会在出现错误时收到通知:

SchemaFactory f = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = f.newSchema(new File("schema.xsd")); 

marshaller.setSchema(schema);
marshaller.setEventHandler(new MyValidationEventHandler());

在您的 ValidationEventHandler 中,您可以根据需要处理验证事件:

public class MyValidationEventHandler implements ValidationEventHandler {
    public boolean handleEvent(ValidationEvent event) {
        // handle validation events
        // if you return false the marshal operation is stopped
    }    
}

关于java - 让 JAXB 在编码到 XML 时强制执行 XSD 限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36336197/

相关文章:

java - 在Java中查找对角线上的5个值

Android - 如何将 Activity 布局膨胀成 fragment ?

xml - 我的 xmlstarlet update 命令有什么问题?

xml - 源解析.4.2 : Error Resolving Component 'ds:Signature'

java - xml节点的文本值到java

Java - 创建一个库并可选导入

java - 网络状态改变时的广播 Intent

java - 如何将这 4 个循环函数简化为 1 个函数?

java - 使用 JAXB 表示法创建嵌套结构

java - 将 JAXB 生成的类用于需要具有模式的整数的元素