Note that there are some explanatory texts on larger screens.

plurals
  1. POJAXB partial-unmarshalling Elements without @XMLRootElement
    primarykey
    data
    text
    <p>I am using the <strong>partial-unmarshalling</strong> example of <strong>JAXB</strong>, but I am unable to unmarshal XML-Elements which are not on the root-level (cause they don't have an @XmlRootElement tag). In my example I tried to read the shipTo-Element instead of the purchaseOrder-Element. </p> <p>Normally I would work with JAXBElement unmarshal(Source source,Class declaredType) but since the example is using an UnmarshallerHandler and a XMLFilterImpl I don't know where to tell Jaxb which Class it should use. </p> <p>My error message is: Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"shipTo"). Expected elements are &lt;{}comment>,&lt;{}purchaseOrder>,&lt;{}purchaseOrders></p> <p>I googled around a lot, but didn't find anything useful yet.</p> <p>Here is the example code from the JaxB-Webpage:</p> <p><em>Main.java</em></p> <pre><code>public class Main { public static void main( String[] args ) throws Exception { // create JAXBContext for the primer.xsd JAXBContext context = JAXBContext.newInstance("primer"); // create a new XML parser SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); XMLReader reader = factory.newSAXParser().getXMLReader(); // prepare a Splitter Splitter splitter = new Splitter(context); // connect two components reader.setContentHandler(splitter); for( int i=0; i&lt;args.length; i++ ) { // parse all the documents specified via the command line. // note that XMLReader expects an URL, not a file name. // so we need conversion. reader.parse(new File(args[i]).toURL().toExternalForm()); } } </code></pre> <p>}</p> <p><em>Splitter.java</em></p> <pre><code>public class Splitter extends XMLFilterImpl { public Splitter( JAXBContext context ) { this.context = context; } /** * We will create unmarshallers from this context. */ private final JAXBContext context; public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if( depth!= 0 ) { // we are in the middle of forwarding events. // continue to do so. depth++; super.startElement(namespaceURI, localName, qName, atts); return; } if( namespaceURI.equals("") &amp;&amp; localName.equals("purchaseOrder") ) { // start a new unmarshaller Unmarshaller unmarshaller; try { unmarshaller = context.createUnmarshaller(); } catch( JAXBException e ) { // there's no way to recover from this error. // we will abort the processing. throw new SAXException(e); } unmarshallerHandler = unmarshaller.getUnmarshallerHandler(); // set it as the content handler so that it will receive // SAX events from now on. setContentHandler(unmarshallerHandler); // fire SAX events to emulate the start of a new document. unmarshallerHandler.startDocument(); unmarshallerHandler.setDocumentLocator(locator); Enumeration e = namespaces.getPrefixes(); while( e.hasMoreElements() ) { String prefix = (String)e.nextElement(); String uri = namespaces.getURI(prefix); unmarshallerHandler.startPrefixMapping(prefix,uri); } String defaultURI = namespaces.getURI(""); if( defaultURI!=null ) unmarshallerHandler.startPrefixMapping("",defaultURI); super.startElement(namespaceURI, localName, qName, atts); // count the depth of elements and we will know when to stop. depth=1; } } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { // forward this event super.endElement(namespaceURI, localName, qName); if( depth!=0 ) { depth--; if( depth==0 ) { // just finished sending one chunk. // emulate the end of a document. Enumeration e = namespaces.getPrefixes(); while( e.hasMoreElements() ) { String prefix = (String)e.nextElement(); unmarshallerHandler.endPrefixMapping(prefix); } String defaultURI = namespaces.getURI(""); if( defaultURI!=null ) unmarshallerHandler.endPrefixMapping(""); unmarshallerHandler.endDocument(); // stop forwarding events by setting a dummy handler. // XMLFilter doesn't accept null, so we have to give it something, // hence a DefaultHandler, which does nothing. setContentHandler(new DefaultHandler()); // then retrieve the fully unmarshalled object try { JAXBElement&lt;PurchaseOrderType&gt; result = (JAXBElement&lt;PurchaseOrderType&gt;)unmarshallerHandler.getResult(); // process this new purchase order process(result.getValue()); } catch( JAXBException je ) { // error was found during the unmarshalling. // you can either abort the processing by throwing a SAXException, // or you can continue processing by returning from this method. System.err.println("unable to process an order at line "+ locator.getLineNumber() ); return; } unmarshallerHandler = null; } } } public void process( PurchaseOrderType order ) { System.out.println("this order will be shipped to " + order.getShipTo().getName() ); } /** * Remembers the depth of the elements as we forward * SAX events to a JAXB unmarshaller. */ private int depth; /** * Reference to the unmarshaller which is unmarshalling * an object. */ private UnmarshallerHandler unmarshallerHandler; /** * Keeps a reference to the locator object so that we can later * pass it to a JAXB unmarshaller. */ private Locator locator; public void setDocumentLocator(Locator locator) { super.setDocumentLocator(locator); this.locator = locator; } /** * Used to keep track of in-scope namespace bindings. * * For JAXB unmarshaller to correctly unmarshal documents, it needs * to know all the effective namespace declarations. */ private NamespaceSupport namespaces = new NamespaceSupport(); public void startPrefixMapping(String prefix, String uri) throws SAXException { namespaces.pushContext(); namespaces.declarePrefix(prefix,uri); super.startPrefixMapping(prefix, uri); } public void endPrefixMapping(String prefix) throws SAXException { namespaces.popContext(); super.endPrefixMapping(prefix); } </code></pre> <p>}</p> <p><em>Primer.xsd</em></p> <pre><code> &lt;xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;xsd:annotation&gt; &lt;xsd:documentation xml:lang="en"&gt; Purchase order schema for Example.com. Copyright 2000 Example.com. All rights reserved. &lt;/xsd:documentation&gt; &lt;/xsd:annotation&gt; &lt;xsd:element name="purchaseOrders"&gt; &lt;xsd:complexType&gt; &lt;xsd:sequence&gt; &lt;xsd:element ref="purchaseOrder" minOccurs="0" maxOccurs="unbounded"/&gt; &lt;/xsd:sequence&gt; &lt;/xsd:complexType&gt; &lt;/xsd:element&gt; &lt;xsd:element name="purchaseOrder" type="PurchaseOrderType"/&gt; &lt;xsd:element name="comment" type="xsd:string"/&gt; &lt;xsd:complexType name="PurchaseOrderType"&gt; &lt;xsd:sequence&gt; &lt;xsd:element name="shipTo" type="USAddress"/&gt; &lt;xsd:element name="billTo" type="USAddress"/&gt; &lt;xsd:element ref="comment" minOccurs="0"/&gt; &lt;xsd:element name="items" type="Items"/&gt; &lt;/xsd:sequence&gt; &lt;xsd:attribute name="orderDate" type="xsd:date"/&gt; &lt;/xsd:complexType&gt; &lt;xsd:complexType name="USAddress"&gt; &lt;xsd:sequence&gt; &lt;xsd:element name="name" type="xsd:string"/&gt; &lt;xsd:element name="street" type="xsd:string"/&gt; &lt;xsd:element name="city" type="xsd:string"/&gt; &lt;xsd:element name="state" type="xsd:string"/&gt; &lt;xsd:element name="zip" type="xsd:decimal"/&gt; &lt;/xsd:sequence&gt; &lt;xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/&gt; &lt;/xsd:complexType&gt; &lt;xsd:complexType name="Items"&gt; &lt;xsd:sequence&gt; &lt;xsd:element name="item" minOccurs="0" maxOccurs="unbounded"&gt; &lt;xsd:complexType&gt; &lt;xsd:sequence&gt; &lt;xsd:element name="productName" type="xsd:string"/&gt; &lt;xsd:element name="quantity"&gt; &lt;xsd:simpleType&gt; &lt;xsd:restriction base="xsd:positiveInteger"&gt; &lt;xsd:maxExclusive value="100"/&gt; &lt;/xsd:restriction&gt; &lt;/xsd:simpleType&gt; &lt;/xsd:element&gt; &lt;xsd:element name="USPrice" type="xsd:decimal"/&gt; &lt;xsd:element ref="comment" minOccurs="0"/&gt; &lt;xsd:element name="shipDate" type="xsd:date" minOccurs="0"/&gt; &lt;/xsd:sequence&gt; &lt;xsd:attribute name="partNum" type="SKU" use="required"/&gt; &lt;/xsd:complexType&gt; &lt;/xsd:element&gt; &lt;/xsd:sequence&gt; &lt;/xsd:complexType&gt; &lt;!-- Stock Keeping Unit, a code for identifying products --&gt; &lt;xsd:simpleType name="SKU"&gt; &lt;xsd:restriction base="xsd:string"&gt; &lt;xsd:pattern value="\d{3}-[A-Z]{2}"/&gt; &lt;/xsd:restriction&gt; &lt;/xsd:simpleType&gt; &lt;/xsd:schema&gt; </code></pre> <p><em>test.xml</em></p> <pre><code>&lt;purchaseOrders&gt; &lt;!-- 1st --&gt; &lt;purchaseOrder orderDate="1999-10-20"&gt; &lt;shipTo country="US"&gt; &lt;name&gt;Alice Smith&lt;/name&gt; &lt;street&gt;123 Maple Street&lt;/street&gt; &lt;city&gt;Cambridge&lt;/city&gt; &lt;state&gt;MA&lt;/state&gt; &lt;zip&gt;12345&lt;/zip&gt; &lt;/shipTo&gt; &lt;billTo country="US"&gt; &lt;name&gt;Robert Smith&lt;/name&gt; &lt;street&gt;8 Oak Avenue&lt;/street&gt; &lt;city&gt;Cambridge&lt;/city&gt; &lt;state&gt;MA&lt;/state&gt; &lt;zip&gt;12345&lt;/zip&gt; &lt;/billTo&gt; &lt;items/&gt; &lt;/purchaseOrder&gt; &lt;/purchaseOrders&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload