JAXB unmarshal with declared type does not populate the resulting object with data

前端 未结 4 1062
孤街浪徒
孤街浪徒 2021-01-21 16:51

I am trying to unmarshal a given XML:


 rewriting of file
 toolA         


        
4条回答
  •  孤城傲影
    2021-01-21 17:48

    Your XML document does not match the namespace qualification that was defined in your mappings (see: http://blog.bdoughan.com/2010/08/jaxb-namespaces.html). You could leverage an XMLFilter to apply a namespace to your XML document during the unmarshal operation.

    import org.xml.sax.*;
    import org.xml.sax.helpers.XMLFilterImpl;
    
    public class NamespaceFilter extends XMLFilterImpl {
    
        private static final String NAMESPACE = "htp://www.example.com/mdf/v4";
    
        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            super.endElement(NAMESPACE, localName, qName);
        }
    
        @Override
        public void startElement(String uri, String localName, String qName,
                Attributes atts) throws SAXException {
            super.startElement(NAMESPACE, localName, qName, atts);
        }
    
    }
    

    Below is an example of how you would leverage the XMLFilter during an unmarshal.

        // Create the XMLFilter
        XMLFilter filter = new NamespaceFilter();
    
        // Set the parent XMLReader on the XMLFilter
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        filter.setParent(xr);
    
        // Set UnmarshallerHandler as ContentHandler on XMLFilter
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        UnmarshallerHandler unmarshallerHandler = unmarshaller
                .getUnmarshallerHandler();
        filter.setContentHandler(unmarshallerHandler);
    
        // Parse the XML
        InputSource xml = new InputSource("input.xml");
        filter.parse(xml);
        Object result = unmarshallerHandler.getResult();
    

    For More Information

    • http://blog.bdoughan.com/2012/11/applying-namespace-during-jaxb-unmarshal.html

提交回复
热议问题