使用JAXB从java对象创建xml

时间:2014-09-24 09:55:46

标签: java xml jaxb

大家好我有java对象,我必须转换为xml。比如像这样的类

package com.test.xml;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

String name;
int age;

public String getName() {
    return name;
}

 @XmlElement
 public void setName(String name) {
    this.name = name;
}

public int getAge() {
    return age;
}

@XmlElement
public void setAge(int age) {
    this.age = age;
}

}

并转换为xml

package com.test.xml;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
 public static void main(String[] args) {

  Customer customer = new Customer();
  customer.setName("testName");
  customer.setAge(25);

  try {

    File file = new File("C:\\testXml.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.marshal(customer, file);
    jaxbMarshaller.marshal(customer, System.out);

    } catch (JAXBException e) {
        e.printStackTrace();
    }

}

}

这会像这样创建xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
  <age>25</age>
  <name>testName</name>
</customer>

和我的问题。如何从这样的Customer对象创建xml?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
  <customerInfo>
    <age>25</age>
    <name>testName</name>
  </customerInfo>
</customer>

1 个答案:

答案 0 :(得分:3)

1.创建客户类

2.创建CustomerInfo类

3.Customer有CustomerInfo

4.现在使用Jaxb创建你的xml文件。