Jaxb解析XML轉換爲JavaBean忽略命名空間

/**
	 * 解析xml(忽略命名空間)
	 * 
	 * @param cla
	 * @param content
	 * @return
	 * @throws JAXBException
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 */
	public static Object unmarshall(Class<?> cla, String content) throws JAXBException, ParserConfigurationException, SAXException {

		JAXBContext jaxbContext = JAXBContext.newInstance(cla);
		Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
		StringReader reader = new StringReader(content);

		SAXParserFactory sax = SAXParserFactory.newInstance();
		sax.setNamespaceAware(false);
		XMLReader xmlReader = sax.newSAXParser().getXMLReader();

		Source source = new SAXSource(xmlReader, new InputSource(reader));
		Object o = unmarshaller.unmarshal(source);

		return o;
	}

先貼上代碼java

 

因爲各類緣由,不少特殊行業的自定義標準命名空間的URL訪問不了,從而致使了Jaxb在將XML內容轉換成JavaBean的時候,獲取命名錯誤,而沒法解析成功!spa

另外一種狀況,在XML中的節點屬性中出現xsi:type、xml:lang等屬性性,要求須要節點對應的對象要與設置的類型進行匹配,本來這是嚴格匹配XML節點格式的行爲,是不錯的方式;但在實際的操做中,這大大增長了數據模型,尤爲是超大型數據模型的製做複雜程序,但願能夠僅將節點與JavaBean進行匹配,相應的數據能填充到數據模型中就好code

設置xml

SAXParserFactory.setNamespaceAware(false);對象

便可在轉換時,忽略命名空間讀取,忽略類型檢查,完成數據轉換get

相關文章
相關標籤/搜索