繁体   English   中英

JAXB编组到XML - 在Schema验证失败时有没有办法处理它?

[英]JAXB marshalling to XML - Is there a way to handle it when Schema validation fails?

我正在使用JAXB来将一些对象编组/解组为XML文件,以用于我想要实现的小型服务。 现在,我有我的XML架构(.xsd文件),其中包含一些unique约束:

<!--....-->
<xs:unique name="uniqueValueID">
    <xs:selector xpath="entry/value"/>
    <xs:field xpath="id"/>
</xs:unique>
<!--....-->

我已将XML模式加载到我的marshaller对象中:

try {
//....
//Set schema onto the marshaller object
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
Schema schema = sf.newSchema(new File(xsdFileName)); 
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.setSchema(schema);

//Apply marshalling here
jaxbMarshaller.marshal(myObjectToMarshall, new File(xmlFileNName));
} catch (JAXBException | SAXException ex) {
   //Exception handling code here....
}

当架构有效时,目标文件会正常更新,但是当验证失败时,文件将被清空或数据不完整。

我猜测问题是marshaller打开了一个文件流,但是当验证失败时,它无法正确处理这种情况。 有没有办法正确处理这个,所以当验证失败时,没有写入操作应用于XML文件?

JAX-B Marshaller将编写各种Java™输出接口。 如果我想确定在编组失败时没有字节写入文件或其他固定实体,我使用字符串缓冲区来包含编组过程的结果,然后编写缓冲区中包含的编组XML文档,就像这样:

     try
     {
        StringWriter output = new StringWriter ();
        JAXBContext jc = JAXBContext.newInstance (packageId);
        FileWriter savedAs;

        // Marshal the XML data to a string buffer here
        Marshaller marshalList = jc.createMarshaller ();
        marshalList.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshalList.marshal (toUpdate, output);

        // append the xml to the file to update here.
        savedAs = new FileWriter (new File (xmlFileName), true);
        savedAs.write (output.toString);
        savedAs.close();
     }
     catch (IOException iox)
     {
        String msg = "IO error on save: " + iox.getMessage ();
        throw new LocalException (msg, 40012, "UNKNOWN", iox);
     }
     catch (JAXBException jbx)
     {
        String msg = "Error writing definitions: " + jbx.getMessage ();
        throw new LocalException (msg, 40005, "UNKNOWN", jbx);
     }
  }

请注意,在此示例中,如果编组过程失败,程序将永远不会创建输出文件,它将简单地丢弃缓冲区字符串。

对于稍微更优雅的风险更高的解决方案,缓冲编写器(java.io.BufferedWriter),允许创建它的调用者设置缓冲区大小。 如果缓冲区大小超过文档的大小,程序可能不会向文件写入任何内容,除非程序在流上调用close或flush。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM