-
t = (T) unmarshaller.unmarshal(new StringReader(xml));
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
return t;
-
}
-
}
非常简单易懂,需要注意的是
-
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
-
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
Marshaller.JAXB_FORMATTED_OUTPUT 决定是否在转换成xml时同时进行格式化(即按标签自动换行,否则即是一行的xml)
Marshaller.JAXB_ENCODING xml的编码方式
另外,Marshaller 还有其他Property可以设置,可以去查阅api。
2、最简单转换
-
package t1;
-
import java.util.Date;
-
import javax.xml.bind.annotation.Xm
lAccessType; -
import javax.xml.bind.annotation.XmlAccessorType;
-
import javax.xml.bind.annotation.XmlAttribute;
-
import javax.xml.bind.annotation.XmlElement;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import javax.xml.bind.annotation.XmlType;
-
/**
-
* @author zhuc
-
* @create 2013-3-29 下午2:49:48
-
*/
-
@XmlAccessorType(XmlAccessType.FIELD)
-
@XmlRootElement
-
@XmlType(name = “book”, propOrder = { “author”, “calendar”, “price”, “id” })
-
public class Book {
-
@XmlElement(required = true)
-
private String author;
-
@XmlElement(name = “price_1”, required = true)
-
private float price;
-
@XmlElement
-
private Date calendar;
-
@XmlAttribute
-
private Integer id;
-
/**
-
* @return the author
-
*/
-
public String getAuthor() {
-
return author;
-
}
-
/**
-
* @return the price
-
*/
-
public float getPrice() {
-
return price;
-
}
-
/**
-
* @return the calendar
-
*/
-
public Date getCalendar() {
-
return calendar;
-
}
-
/**
-
* @return the id
-
*/
-
public Integer getId() {
-
return id;