Jaxb简介
JavaTM Architecture for XML Binding (JAXB) 提供了api 和工具用于自动映射XML文档和Java对象。 JAXB框架允许开发者执行以下的操作: 通过schema 生成相应的java 源文件 访问以及更新相应的java 源文件 配置java 源文件,生成相应的schema JAXB 给了java 开发者一种有效的和标准的方式用于映射xml和java 代码。java开发者使用JAXB能提供生产力,由于只需要写很少的代码,不需要成为xml方面的专家。JAXB 对于开发者来说更容易扩展他们的应用,使用XML或者web services技术。 看一个简单的例子: 从xsd文件生成相应的java 文件 xsd 文件配置如下: 定义ant build : 主要的内容如下: 定义xjc任务,用于从schema 中生成相应的java 文件 执行xjc 执行ant 任务后产生的java 文件如下: foo.java @XmlAccessorType(AccessType.FIELD) @XmlType(name = "foo", propOrder = { "age" }) public class Foo { @XmlElement(type = Integer.class) protected int age; /** * Gets the value of the age property. * */ public int getAge() { return age; } /** * Sets the value of the age property. * */ public void setAge(int value) { this.age = value; } } ObjectFactory.java 主要的产生类,作为工厂类 @XmlRegistry public class ObjectFactory { private final static QName _Root_QNAME = new QName("", "root"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: generated * */ public ObjectFactory() { } /** * Create an instance of {@link Foo } * */ public Foo createFoo() { return new Foo(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Foo }{@code >}} * */ @XmlElementDecl(namespace = "", name = "root") public JAXBElement createRoot(Foo value) { return new JAXBElement(_Root_QNAME, Foo.class, null, value); } } 比较简单的实现,不过主要的工作还是用来通过java类来生成相应的xml文件: 测试方法: public static void main(String[] args) throws Exception { JAXBContext context = JAXBContext.newInstance(ObjectFactory.class); ObjectFactory of = new ObjectFactory(); Foo foo = new Foo(); foo.setAge(11); JAXBElement e = of.createRoot(foo); //用于输出元素 Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); FileOutputStream stream = new FileOutputStream(new File(args[0])); marshaller.marshal(e, stream); } 生成的xml如下: 11