在Spring Boot中接受带有或不带有名称空间的XML

时间:2018-10-23 17:55:13

标签: java xml namespaces

我有一个旧版应用程序,试图将其迁移到我的Spring Boot应用程序中,并且XML名称空间有问题。


我希望我的Spring Boot应用程序能够接受带有或不带有名称空间的XML。例如,

带有命名空间

<?xml version="1.0" encoding="iso-8859-1"?>
<NotificationRequest 
xmlns="http://request.xmlbeans.cpc.com/NotificationQuery"   
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
</NotificationRequest>

并且没有名称空间

<?xml version="1.0" encoding="iso-8859-1"?>
<NotificationRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
</NotificationRequest>

我已经为命名空间创建了package-info

@javax.xml.bind.annotation.XmlSchema(namespace = 
"http://request.xmlbeans.cpc.com/NotificationQuery", elementFormDefault = 
javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.onem.xmlbeans.request;

但是,这将接受带有命名空间的XML,但不接受没有命名空间的XML。


我的代码如下:

@RequestMapping(method = RequestMethod.POST, consumes = 
MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = 
MediaType.APPLICATION_XML_VALUE)
public SMSHistoryResponse getSMSHistory(@RequestParam("xmlreq") String       
    request ) {
    SMSHistoryRequest requestObj = new SMSHistoryRequest();
    JAXBContext jaxbContext;
    try {
        // Convert the incoming String XML into POJO 
        jaxbContext = JAXBContext.newInstance(SMSHistoryRequest.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        StringReader reader = new StringReader(request);
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, 
        false);
        XMLStreamReader xsr = xif.createXMLStreamReader(new 
        StreamSource(reader));
        requestObj = (SMSHistoryRequest) unmarshaller.unmarshal(xsr);
        } catch(JAXBException e) {
            e.printStackTrace();
            LOGGER.error("JAXB exception parsing error" + e.getMessage());
        } catch(XMLStreamException e) {
            LOGGER.error("XML Stream exception " + e.getMessage());
        }
        return smsBuilder.searchSMSHistory(requestObj);
    }

当它解组XML(没有名称空间)时,出现以下错误:

javax.xml.bind.UnmarshalException - with linked exception: [com.sun.istack.internal.SAXParseException2; lineNumber: 2; columnNumber: 22; unexpected element (uri:"", local:"NotificationRequest"). Expected elements are <{http://request.xmlbeans.cpc.com/NotificationQuery}NotificationRequest>]

0 个答案:

没有答案