JAXB学习笔记(五)
上个例子中生成的xml
Xml代码
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persion>
<userid name="userid">112</userid>
<username name="username">就不告诉你</username>
<birthday name="birthday">2011-09-28</birthday>
</persion>
人说这都"什嘛",可能我们真正需要的是这样子的,即节点名字叫"field"
Xml代码
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persion>
<field name="userid">112</userid>
<field name="username">就不告诉你</username>
<field name="birthday">2011-09-28</birthday>
</persion>
OK,有需求咱们就要解决,当然处理这个之前我们先要知道集合的序列化,因为明显我们看出field节点是一组数组集合。上代码
Java代码
package cn.uyunsky.blog.xml.demo5;
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.XmlRootElement;
/**
* <p>集合试验</p>
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Persion {
private List<String> infos;
public List<String> getInfos() {
return infos;
}
public void setInfos(List<String> 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<String> infos = new ArrayList<String>();
infos.add("112");
infos.add("就不告诉你");
infos.add(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
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();
}
}
}
输出结果
Xml代码
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persion>
<infos>112</infos>
<infos>就不告诉你</infos>
<infos>2011-09-28</infos>
</persion>
Persion [infos=[112, 就不告诉你, 2011-09-28]]
好了,下一节我们最后看看本节开头提到的xml格式怎么实现
作者“有云的天空”
补充:软件开发 , Java ,