天天看點

javax.xml.bind.UnmarshalException:元素 "soap:Envelope" 的字首 "soap" 未綁定。

Jaxb解析xml(帶命名空間)相關聯的屬性 “xsi:NamespaceSchemaLocation” 的字首 “xsi” 未綁定。 - sidihuo的專欄 - CSDN部落格

https://blog.csdn.net/sidihuo/article/details/50478178

Jaxb解析xml(帶命名空間)相關聯的屬性 “xsi:NamespaceSchemaLocation” 的字首 “xsi” 未綁定。

final JAXBContext context = JAXBContext.newInstance(XlvdDiagram.class);
final Unmarshaller unmarshaller = context.createUnmarshaller();
final FileReader reader = new FileReader(new File(path));
final SAXParserFactory sax = SAXParserFactory.newInstance();
sax.setNamespaceAware(false);// 忽略命名空間
final XMLReader xmlReader = sax.newSAXParser().getXMLReader();
final SAXSource saxSource = new SAXSource(xmlReader, new InputSource(reader));
final Object object = unmarshaller.unmarshal(saxSource);
--------------------- 
作者:四滴火 
來源:CSDN 
原文:https://blog.csdn.net/sidihuo/article/details/50478178 
版權聲明:本文為部落客原創文章,轉載請附上博文連結!
           

我的報錯資訊:

在将SOAP規範的xml轉為java bean時報錯了:

javax.xml.bind.UnmarshalException

with linked exception:

[org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 334; 元素 “soap:Envelope” 的字首 “soap” 未綁定。]

xml到java bean的轉換方法:

@SuppressWarnings("unchecked")
	public static <T> T xml2Object(String xmlStr, Class<T> c) 
			throws JAXBException, SAXException, ParserConfigurationException {
		JAXBContext context = JAXBContext.newInstance(c);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		T t = (T) unmarshaller.unmarshal(new StringReader(xmlStr));
		return t;
}
           

按照上述部落格介紹的修改xml到java bean的轉換方法:

/**
     * xml轉換成JavaBean
     *
     * @param xml xml格式字元串
     * @param t   待轉化的對象
     * @return 轉化後的對象
     * @throws Exception JAXBException
     */
    @SuppressWarnings("unchecked")
    public static <T> T convertToJavaBean(String xml, Class<T> t) throws Exception {
        T obj = null;
        StringReader reader = null;
        try {
            JAXBContext context = JAXBContext.newInstance(t);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            reader = new StringReader(xml);
            SAXParserFactory sax = SAXParserFactory.newInstance();
            sax.setNamespaceAware(false); // 忽略命名空間
            XMLReader xmlReader = sax.newSAXParser().getXMLReader();
            Source source = new SAXSource(xmlReader, new InputSource(reader));
            obj = (T) unmarshaller.unmarshal(source);
            return obj;
        } catch (Exception e) {
        	e.printStackTrace();
        	throw new RuntimeException("解析SOAP封包失敗!");
        }finally {
            if(reader!=null){
                reader.close();
            }
        }
    }