//xml轉換成bean public static RequestXML parseToBean(String xmlstr) { RequestXML requestXml = null; try { JAXBContext jaxbContext = JAXBContext.newInstance(RequestXML.class); Unmarshaller um = jaxbContext.createUnmarshaller(); requestXml = (RequestXML)um.unmarshal(new ByteArrayInputStream(xmlstr.getBytes())); } catch (JAXBException e) { e.getMessage(); } return requestXml; } //bean 轉換成 xml private static String parseToXml(Object javaBean) throws Exception{ JAXBContext context = JAXBContext.newInstance(xmlBean.getClass()); Marshaller m = context.createMarshaller(); StringWriter sw = new StringWriter(); m.marshal(javaBean,sw); return sw.toString(); }
JAXB 結構:
xml example:
<?xml version="1.0" encoding="utf-8"?><bean id="10" code="xm1000x"> <name>x.m<name> <levels> <level key="1">none</level> <level key="2">nothing</level> </levels> <extras> <extra> <type>1</type> <content>xx.mm.xx</content> </extra> <extra> <type>2</type> <content>xx.mm.xx</content> </extra> </extras> </bean>
java bean:
import java.util.ArrayList;import java.util.List;import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlElementWrapper;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name="bean")public class Bean {private Integer id;private String code;private String name;private List<Level> levels = new ArrayList<Level>();private List<Extra> extras = new ArrayList<Extra>();public Bean(){}@XmlAttributepublic Integer getId() {return id;}@XmlAttributepublic String getCode() {return code;}@XmlElementpublic String getName() {return name;}@XmlElementWrapper(name="levels")@XmlElement(name="level")public List<Level> getLevels() {return levels;}@XmlElementWrapper(name="extras")@XmlElement(name="extra")public List<Extra> getExtras() {return extras;}public void setId(Integer id) {this.id = id;}public void setCode(String code) {this.code = code;}public void setName(String name) {this.name = name;}public void setLevels(List<Level> levels) {this.levels = levels;}public void setExtras(List<Extra> extras) {this.extras = extras;}}
import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlValue;@XmlRootElementpublic class Level { private Integer Key; private String value; public Level(){} @XmlAttribute(name="key") public Integer getKey() { return Key; } @XmlValue public String getValue() { return value; } public void setKey(Integer key) { Key = key; } public void setValue(String value) { this.value = value; } }
import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class Extra { private String type; private String content; public Extra(){} @XmlElement public String getType() { return type; } @XmlElement public String getContent() { return content; } public void setType(String type) { this.type = type; } public void setContent(String content) { this.content = content; } }