JAXB解析XML

嘗試過dom4j和XStream,二者對於XML轉java bean都比較無力。最終JAXB解煩憂。

主要問題出現在構建pojo類上:

*出現在XML裏的標籤,都應該是pojo中的字段名。

*List都以數組形式表達,數組的字段名變成每一個元素的標籤名。

<ALL>
<PNRNO />
<PASSENGERLIST>
    <PASSENGER>
        <NAME>1</NAME>
    </PASSENGER>
    <PASSENGER>
        <NAME>2</NAME>
    </PASSENGER>
    <PASSENGER>
        <NAME>3</NAME>
    </PASSENGER>
</PASSENGERLIST>
</ALL>

應表示爲

@XmlRootElement(name = "ALL")
public class ALL {
    @XmlElement
    public PassengerList PASSENGERLIST;
    
    @XmlRootElement
    public static class PassengerList {
        @XmlElement
        Passenger[] PASSENGER;
    }
}

註解使用參考:

http://blog.csdn.net/chen7788/article/details/7384315

http://blog.csdn.net/czplplp_900725/article/details/7888896


JAXB實現XML和java bean的互轉:

    /**
     * 將Java對象序列化爲XML字符串
     *
     * @param pojo 待序列化的Java對象
     * @throws JAXBException
     * @return
     */
	public static String toXml(Object pojo) throws JAXBException {
		JAXBContext jaxbContext = JAXBContext.newInstance(pojo.getClass());
		Marshaller marshaller = jaxbContext.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); //編碼格式
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //是否格式化生成的XML
		marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false); // 是否省略XML頭聲明信息
		StringWriter stringWriter = new StringWriter();
		marshaller.marshal(pojo, stringWriter);
		return stringWriter.toString();
	}


    /**
     * 將XML字符串反序列化爲Java對象
     *
     * @param xmlStr 待反序列化的XML字符串
     * @param pojoClass 需要反序列化的類型
     * @throws JAXBException
     * @return
     */
	public static <T> Object fromXml(String xmlStr, Class<T> pojoClass) throws JAXBException {
		JAXBContext jaxbContext = JAXBContext.newInstance(pojoClass);
		Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
		Object object = unmarshaller.unmarshal(new ByteArrayInputStream(xmlStr.getBytes()));
		return object;
	}



發佈了25 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章