这里介绍一个强大的工具jaxb,其实jdk就有这个功能,但是感觉不怎么强大,而且jaxb还可以根据xsd结构来生成对象。有空会介绍
1、javabean对象
@XmlRootElement(name = "beans") @XmlAccessorType(XmlAccessType.NONE) public class Beans { @XmlElement(name = "bean") private List<Bean> beanList; public List<Bean> getBeanList() { return beanList; } public void setBeanList(List<Bean> beanList) { this.beanList = beanList; } }
这个是根对象,如果根对象只有1个元素完全可以用@XmlElementWrapper来代替,但是为了更好的扩展我这里使用一般的定义
这个特别注明的是
@XmlAccessorType的默认访问级别是XmlAccessType.PUBLIC_MEMBER,因此,如果java对象中的private成员变量设置了public权限的getter/setter方法,就不要在private变量上使用@XmlElement和@XmlAttribute注解,否则在由java对象生成xml时会报同一个属性在java类里存在两次的错误。同理,如果@XmlAccessorType的访问权限为XmlAccessType.NONE,如果在java的成员变量上使用了@XmlElement或@XmlAttribute注解,这些成员变量依然可以映射到xml文件。
我们这样可以自己控制要生成的对象
@XmlAccessorType(XmlAccessType.NONE) public class Bean { @XmlAttribute(name = "id") private String id; @XmlAttribute(name = "class") private String className; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; }
子节点 这里就没什么好说的。
2、具体实现
具体的实现很简单
先看marshaller
public static void marshallerByJaxb(String path, Object object, Class clazz) throws JAXBException, IOException { JAXBContext jc = JAXBContext.newInstance(clazz); Marshaller marshaller = jc.createMarshaller(); File file = new File(path); if (!file.exists()) { file.createNewFile(); } marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(object, file); }
调用
Beans beans = new Beans(); List<Bean> list = new ArrayList<Bean>(); Bean beanOne = new Bean(); beanOne.setClassName("testClassOne"); beanOne.setId("testIdOne"); Bean beanTwo = new Bean(); beanTwo.setClassName("testClassTwo"); beanTwo.setId("testIdTwo"); list.add(beanOne); list.add(beanTwo); beans.setBeanList(list); XMLTransformed.marshallerByJaxb("test.xml", beans, Beans.class);
最后生成的xml
<beans> <bean id="testIdOne" class="testClassOne"/> <bean id="testIdTwo" class="testClassTwo"/> </beans>
最后看unmarshaller
public static Object unmarshallerByJaxb(String path, Class clazz) throws JAXBException, IOException { JAXBContext jc = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = jc.createUnmarshaller(); File file = new File(path); if (!file.exists()) { throw new FileNotFoundException("Can not load xml file!"); } return unmarshaller.unmarshal(file); }