2014-09-24 54 views
2

大家好我有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 version="1.0" encoding="UTF-8" standalone="yes"?> 
<customer> 
    <age>25</age> 
    <name>testName</name> 
</customer> 

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

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

回答

3

1.创建一个Customer类

2.创建CustomerInfo类

3.客户有CustomerInfo

4.Now创建使用JAXB XML文件。

+0

非常感谢。 – shms 2014-09-24 11:30:02