title: How can I validate my XML using a schema, reading only one object/element at a time by JAXB's XMLStreamReader?
body: <p>The code below works correctly to unmarshal XML from the stream one object at a time.</p>
  
  <p>But when I un-comment the <code>unmarshaller.setSchema(schema)</code> line the program throws an exception:</p>
  
  <blockquote>
    <p>[org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'Subscriber'.]</p>
  </blockquote>
  
  <p>I have already validated the XML using the <code>javax.xml.validation.Validator</code> class, but my goal is to validate and unmarshal at the same time, one element at a time.</p>
  
  <p>This is my current code:</p>
  
  <pre><code>SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
  Schema schema = sf.newSchema(new File("/Path to xsd"));
  
  XMLInputFactory inputFactory = XMLInputFactory.newInstance();
  XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new FileReader("/Path to xml"));
  
  JAXBContext jaxbContext = JAXBContext.newInstance(SubscriberType.class);
  Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
  //unmarshaller.setSchema(schema);
  
  streamReader.nextTag();
  streamReader.require(XMLStreamConstants.START_ELEMENT, null, "Subscribers");
  streamReader.nextTag();    
  while (streamReader.getEventType() == XMLStreamConstants.START_ELEMENT) {
  
      JAXBElement&lt;SubscriberType&gt; pt = unmarshaller.unmarshal(streamReader, SubscriberType.class);
      //do something with the unmarshalled object pt...store to db ect.
  
      if (streamReader.getEventType() == XMLStreamConstants.CHARACTERS) {
          streamReader.next();
      }
  }
  </code></pre>
  
  <p>Excerpt of my schema subscriber.xsd:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
  &lt;xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          elementFormDefault="unqualified" 
          attributeFormDefault="unqualified"&gt;
  
    &lt;xsd:element name="Subscribers" type="SubscriberType" /&gt;
  
    &lt;xsd:complexType name="SubscriberType"&gt;
      &lt;xsd:sequence&gt;
        &lt;xsd:element name="Subscriber" 
                type="SubscriberInformation" 
                minOccurs="1" 
                maxOccurs="unbounded"/&gt;
      &lt;/xsd:sequence&gt;
    &lt;/xsd:complexType&gt;
  </code></pre>