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


i using jaxb in order marshall/unmarshall objects xml file small service want implement. right now, have xml schema (.xsd file) includes unique constraints:

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

i have loaded xml schema marshaller object:

try { //.... //set schema onto 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.... } 

when schema valid target file updated normally, when validation fails, file emptied or incomplete data.

i guessing problem marshaller opens file stream, when validation fails, not handle situation properly. there way handle this, when validation fails, no writing operation applied xml file?

the jax-b marshaller write wide variety of java™ output interfaces. if want make quite no bytes written file or other fixed entity should marshalling fail, use string buffer contain results of marshalling process, write marshalled xml document contained in buffer, so:

     try      {         stringwriter output = new stringwriter ();         jaxbcontext jc = jaxbcontext.newinstance (packageid);         filewriter savedas;          // marshal xml data string buffer here         marshaller marshallist = jc.createmarshaller ();         marshallist.setproperty (marshaller.jaxb_formatted_output, true);         marshallist.marshal (toupdate, output);          // append xml file 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);      }   } 

note in example, if marshalling process fails, program never create output file , discard buffer string.

for more elegant if riskier solution, buffered writer (java.io.bufferedwriter), allows caller creates set buffer size. if buffer size exceeds size of document, program not write file unless program calls close or flush on stream.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -