shms
shms

Reputation: 79

create xml from java object using JAXB

Hi all i have java object which i have to convert to xml. For example class like this

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;
}

}

and convert to 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();
    }

}

}

this will create xml like this

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

and my question. how to create xml from Customer object like this?

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

Upvotes: 2

Views: 1006

Answers (1)

pd30
pd30

Reputation: 240

1.Create a Customer class

2.Create a CustomerInfo class

3.Customer has CustomerInfo

4.Now create using Jaxb your xml file.

Upvotes: 4

Related Questions