Sure! I can provide you with a simple example of JAXB (Java Architecture for XML Binding) for marshalling and unmarshalling Java objects to XML.
JAXB provides a way to convert Java objects to XML representation (marshalling) and XML to Java objects (unmarshalling) using annotations.
Here's an example that demonstrates the marshalling and unmarshalling process: Create a Java class representing the object you want to marshal and unmarshal.
Let's say we have a Person class with name and age attributes:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Marshal the Person object to XML:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class MarshallingExample {
public static void main(String[] args) {
try {
// Create a Person object
Person person = new Person();
person.setName("John Doe");
person.setAge(30);
// Create a JAXBContext
JAXBContext context = JAXBContext.newInstance(Person.class);
// Create a Marshaller
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Marshal the Person object to XML
marshaller.marshal(person, System.out);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In this example, we create a Person object and set its name and age attributes.
Then, we create a JAXBContext for the Person class and a Marshaller to convert the object to XML.
We set the JAXB_FORMATTED_OUTPUT property to true for pretty-printing the XML output. Finally, we invoke the marshal method on the Marshaller object, passing in the Person object and the output stream (System.out) to print the XML.
Unmarshal the XML back to a Java object:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
public class UnmarshallingExample {
public static void main(String[] args) {
try {
// XML representation of the Person object
String xml = "John Doe 30 ";
// Create a JAXBContext
JAXBContext context = JAXBContext.newInstance(Person.class);
// Create an Unmarshaller
Unmarshaller unmarshaller = context.createUnmarshaller();
// Unmarshal the XML back to a Person object
Person person = (Person) unmarshaller.unmarshal(new StringReader(xml));
// Print the values of the Person object
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
} catch (Exception e) {
e.printStackTrace();
}
}
}
In this example, we have an XML representation of the Person object as a string. We create a JAXBContext for the Person class and an Unmarshaller to convert the XML to a Java object.
We invoke the unmarshal method on the Unmarshaller, passing in a StringReader with the XML string. The returned object is cast to a Person object, and we
No comments:
Post a Comment