java对象转化成xml文件

时间:2022-10-24 06:42:03

第一步:定义将要转化的Java对象

ackage step1.wrapper;  

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

@XmlRootElement
public class Customer {
String[] names;
int age;
int id;

//使用@XmlElementWrapper注解后,将会在原xml结点上再包装一层xml
@XmlElementWrapper(name="allnames")
@XmlElement(name="myname")
public String[] getNames() {
return names;
}
public void setNames(String[] names) {
this.names = names;
}

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

@XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}

@Override
public String toString() {
return "Customer [id=" + id + ",names=" + names + ",age=" + age + "]";
}
}

第二步:编组

package step1.wrapper; 

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

//Marshaller
public class Object2XmlDemo {
public static void main(String[] args) {

Customer customer = new Customer();
customer.setId(100);
customer.setNames(new String[]{"name-a","name-b","name-c"});
customer.setAge(29);
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
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 id="100">
<age>29</age>
<allnames>
<myname>name-a</myname>
<myname>name-b</myname>
<myname>name-c</myname>
</allnames>
</customer>

其中对于java实体类中的注解进行解释
@XmlRootElement 根节点
@XmlRootElement(name=”customer”)
可以这样表示
*@XmlElementWrappe*r
使用@XmlElementWrapper注解后,将会在原xml结点上再包装一层xml
注:@XmlElementWrapper仅允许出现在集合属性上。
@XmlElement:
该属性作为xml的element,且可以增加属性(name=”NewElementName”),那么生成的xml串的elment的标签是NewElementName