一定义一个实体类
package lucence;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Book {
private String name;
private String sex;
private String aa;
public String getName() {
return name;
}
public Book(){
}
public Book(String name, String sex, String aa) {
super();
this.name = name;
this.sex = sex;
this.aa = aa;
}
@Override
public String toString() {
return "Book [name=" + name + ", sex=" + sex + ", aa=" + aa + "]";
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAa() {
return aa;
}
public void setAa(String aa) {
this.aa = aa;
}
}
记得加上@XmlRootElement的注解
package lucence;
import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class TestMain {
public static void main(String[] args) throws JAXBException {
Book b=new Book("fsdadf","dfs","fdsa");
//对象转化成xml
changeObjToXml(b);
//<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><book><aa>fdsa</aa><name>fsdadf</name><sex>dfs</sex></book>
//xml转化成对象
String xml="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><book><aa>fdsa</aa><name>fsdadf</name><sex>dfs</sex></book>";
changXmlToObj(xml);
//Book [name=fsdadf, sex=dfs, aa=fdsa]
}
private static void changXmlToObj(String xml) throws JAXBException {
// TODO Auto-generated method stub
JAXBContext context=JAXBContext.newInstance(Book.class);
Unmarshaller createUnmarshaller = context.createUnmarshaller();
Book unmarshal = (Book) createUnmarshaller.unmarshal(new StringReader(xml));
System.out.println(unmarshal.toString());
}
//Book [name=fsdadf, sex=dfs, aa=fdsa]
private static Book changeObjToXml(Book b) throws JAXBException {
JAXBContext jaxbContext=JAXBContext.newInstance(Book.class);
Marshaller createMarshaller = jaxbContext.createMarshaller();
createMarshaller.marshal(b, System.out);
return b;
}
}