2010-07-25 14 views
5
  1. Ho scritto alcune classi Java e le ho annotate con le annotazioni JAXB.
  2. Dopo che ho usato schemagen per generare un XSD.
  3. Poi ho costruire un oggetto grafico e radunate in un file XML.
  4. ho modificato il file XML in modo che non era più valido.

Volevo usare xsd nella speranza che l'unmarshalling di JAXB fallisse. Ma non è così. Perché?Perché JAXB non vuole convalidare

JAXB sta leggendo uno schema (se lo schema XML è errato, JAXB fornisce un'eccezione) ma giustamente JAXB ignora lo schema durante la lettura.

SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); 
Schema schema = sf.newSchema(getClass().getResource("/schema1.xsd")); 
JAXBContext context = JAXBContext.newInstance(Customer.class); 
Unmarshaller unmarshaller = context.createUnmarshaller(); 
unmarshaller.setSchema(schema); 

Customer c = JAXB.unmarshal(file, Customer.class); 

L'XML scritto inizia così:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<ns2:customer xmlns:ns2="http://bla.com/"> 

Anche il ValidationEventCollector allegato non ha dato alcuna informazione:

unmarshaller.setEventHandler(new JAXBEventCollector()); 

JAXBEventCollector è:

class JAXBEventCollector extends ValidationEventCollector 
{ 
    @Override 
    public boolean handleEvent(ValidationEvent event) 
    { 
     System.out.println(event.getLocator()); 
     return true; 
    } 
} 
+0

Duplicate: http://stackoverflow.com/questions/805989/can -one-validate-marshalled-xml-with-jaxb-2-0 – lexicore

+0

Ovviamente no. Si prega di prendere il tempo e leggere attentamente entrambe le domande. –

+0

come da duplice errore lessicale - votato per chiudere –

risposta

2

tuo codice shoul d lavoro. Un paio di cose a cui prestare attenzione:

  • L'URL per il tuo schema torna come null?
  • è la vostra ultima linea di un errore di battitura "JAXB.unmarshal (file, Customer.class)", o è un'altra JAXB unmarshaller senza uno schema impostato su di esso.

Di seguito è riportato un frammento di codice che genera sicuramente errori quando l'XML non valido non viene risolto. Questo codice funziona correttamente con entrambe le implementazioni JAXB MOXy e Metro (RI).

public static void main(String[] args) throws Exception { 
    SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); 
    File xsd = new File("customer.xsd"); 
    Schema schema = sf.newSchema(xsd); 
    JAXBContext context = JAXBContext.newInstance(Customer.class); 
    Unmarshaller unmarshaller = context.createUnmarshaller(); 
    unmarshaller.setSchema(schema); 

    FileInputStream xml = new FileInputStream("invalid.xml"); 
    unmarshaller.unmarshal(xml); 
} 

Con Metro l'errore si presenta come:

Exception in thread "main" javax.xml.bind.UnmarshalException 
- with linked exception: 
[org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'phone-numbers'. One of '{phoneNumbers}' is expected.] 
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:315) 
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:514) 
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:215) 
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:184) 
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137) 
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:184) 
    at example.gettingstarted.Demo2.main(Demo2.java:23) 

Con Moxy l'errore si presenta come:

Exception in thread "main" javax.xml.bind.UnmarshalException 
- with linked exception: 
[Exception [EclipseLink-25004] (Eclipse Persistence Services - 2.0.3.qualifier): org.eclipse.persistence.exceptions.XMLMarshalException 
Exception Description: An error occurred unmarshalling the document 
Internal Exception: org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'phone-numbers'. One of '{phoneNumbers}' is expected.] 
    at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:114) 
    at example.gettingstarted.Demo2.main(Demo2.java:23) 
+1

Se l'URL dello schema fosse errato, sarebbe presente una NullPointerException. Quindi questo non è l'errore. Ma tu mi hai indirizzato all'errore e ho potuto sbattere la testa contro il muro. Grazie! Tu fai la mia giornata :) Ovviamente JAXB.unmarshal() non ha il contesto, giusto è Cliente c = (Cliente) unmarshaller.unmarshal (file); –

+0

Nessun problema, sentiti libero di votare o accettare come risposta se ti aiuta :) –

Problemi correlati