在NetBeans下将Java对象映射到XML文档
新建一个Java Application 工程Marshaller.
创建一个类Person,代码如下:
package freebird;
/**
*
* @author Administrator
*/
public class Person {
private String name;
private String sex;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the sex
*/
public String getSex() {
return sex;
}
/**
* @param sex the sex to set
*/
public void setSex(String sex) {
this.sex = sex;
}
}
在Main类的main函数内部空白处添加 jaxbm ,然后按下tab键,会自动生成如下代码:
public static void main(String[] args) {
try {
javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(args.getClass().getPackage().getName());
javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller();
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); //NOI18N
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(args, System.out);
} catch (javax.xml.bind.JAXBException ex) {
// XXXTODO Handle exception
java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, null, ex); //NOI18N
}
}
在try块内的第一行添加创建Person实例的代码,其余代码两处改动:
public static void main(String[] args) {
try {
Person p=new Person();
p.setName("chenshu");
p.setSex("male");
javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(new Class[]{freebird.Person.class}
);
javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller();
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); //NOI18N
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(p
, System.out);
} catch (javax.xml.bind.JAXBException ex) {
// XXXTODO Handle exception
java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, null, ex); //NOI18N
}
}
注意,最后一行参数是System.out,所以结果将打印到标准输出窗口,如果我们传递代表文件的参数,那么将打印到文件。可以用下面的代码进行替换:
FileOutputStream stream=new FileOutputStream("c:/Person.xml");
marshaller.marshal(p
, stream);
运行,出现报错误信息:unable to marshal type "freebird.Person" as an element because it is missing an @XmlRootElement annotation]
在Person类前面添加如下代码:
@XmlRootElement(name="Test",namespace="freebird")
public class Person {
运行,输出结果为:
我们完全可以将static void main方法加到Person类中,这样,只要运行这个文件(Person.java),就可以得到我们想要的xml文档。