JAXB sorts XML - Is there a way to handle this when schema validation fails?

I am using JAXB

marshall / unmarshall to order some objects in an XML file for a small service that I want to implement. Right now I have my XML Schema (.xsd file) which contains some restrictions unique


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


I loaded my XML schema into my marshaller object:

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);

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


When the schema is valid, the target file is updated normally, but when validation fails, the file is flushed or with incomplete data.

I guess the problem is that the marshaller opens a stream of files, but when the check fails, it doesn't handle the situation as expected. Is there a way to properly handle this so that when validation fails, no write operation is applied to the XML file?


source to share

1 answer

JAX-B Marshaller will write for a wide variety of Java β„’ withdrawal. If I want to completely ensure that no bytes are written to a file or other fixed object if the marshalling fails, I use a string buffer to contain the results of the sorting process, and then write the marshaled XML document contained in the buffer, for example

        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);
     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);


Note that in this example, if the sorting process is not running, the program will never create an output file, and it will simply discard the buffer line.

For a slightly more elegant, if riskier solution, a buffered writer (java.io.BufferedWriter) that allows the caller who creates it to set the buffer size. If the buffer exceeds the size of the document, the program will probably not write anything to the file unless the program closes or starts the stream in the stream.



All Articles