JAXB学习笔记(六)
上节中所说的最终xml格式,
Xml代码
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persion>
<filed name="userid">112</filed>
<filed name="username">就不告诉你</filed>
<filed name="birthday">2011-09-28</filed>
</persion>
聪明的读者应该自己就会实现了,通过集合+属性值的方式就ok了,看代码
Java代码
package cn.uyunsky.blog.xml.demo6;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* <p>属性+集合 实现非正常思维的xml</p>
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Persion {
@XmlElement(name = "filed")
private List<DemoField> infos;
public List<DemoField> getInfos() {
return infos;
}
public void setInfos(List<DemoField> infos) {
this.infos = infos;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Persion [infos=");
builder.append(infos);
builder.append("]");
return builder.toString();
}
public static void main(String[] args) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Persion.class);
Persion persion = new Persion();
List<DemoField> infos = new ArrayList<DemoField>();
DemoField userid = new DemoField();
userid.setName("userid");
userid.setValue("112");
infos.add(userid);
DemoField username = new DemoField();
username.setName("username");
username.setValue("就不告诉你");
infos.add(username);
DemoField birthday = new DemoField();
birthday.setName("birthday");
birthday.setValue(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
infos.add(birthday);
persion.setInfos(infos);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(persion, writer);
String xml = writer.getBuffer().toString();
System.out.println(xml);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Object bean = unmarshaller.unmarshal(new StringReader(xml));
System.out.println(bean);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
DemoField对象
Java代码
package cn.uyunsky.blog.xml.demo6;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;
@XmlAccessorType(XmlAccessType.FIELD)
public class DemoField {
@XmlAttribute
private String name;
@XmlValue
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
StringBuilder
补充:软件开发 , Java ,