Java objects to xml string

JAXB Write Java Object to XML Example

Java example to write Java object to XML. Information stored in Java objects fields can written into XML file or simply XML string as well.

1) Convert Java Object to XML String

To write Java object to XML String , first get the JAXBContext . It is entry point to the JAXB API and provides methods to unmarshal, marshal and validate operations.

Now get the Marshaller instance from JAXBContext . It’s marshal() method marshals Java object into XML. Now this XML can be written to different outputs e.g. string, file or stream.

package com.howtodoinjava.demo; import java.io.File; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class JaxbExample < public static void main(String[] args) < //Java object. We will convert it to XML. Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT")); //Method which uses JAXB to convert object to XML jaxbObjectToXML(employee); >private static void jaxbObjectToXML(Employee employee) < try < //Create JAXB Context JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); //Create Marshaller Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); //Required formatting?? jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); //Print XML String to Console StringWriter sw = new StringWriter(); //Write XML to StringWriter jaxbMarshaller.marshal(employee, sw); //Verify XML Content String xmlContent = sw.toString(); System.out.println( xmlContent ); >catch (JAXBException e) < e.printStackTrace(); >> >

2) Convert Java Object to XML File

Writing XML to file is very similar to above example. You only need to provide XML file location where you want to write the file.

package com.howtodoinjava.demo; import java.io.File; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class JaxbExample < public static void main(String[] args) < //Java object. We will convert it to XML. Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT")); //Method which uses JAXB to convert object to XML jaxbObjectToXML(employee); >private static void jaxbObjectToXML(Employee employee) < try < //Create JAXB Context JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); //Create Marshaller Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); //Required formatting?? jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); //Store XML to File File file = new File("employee.xml"); //Writes XML file to file-system jaxbMarshaller.marshal(employee, file); >catch (JAXBException e) < e.printStackTrace(); >> >

If you want to read the XML from file to Java object again, then use this method.

String fileName = "employee.xml"; //Call method which read the XML file above jaxbXmlFileToObject(fileName); private static void jaxbXmlFileToObject(String fileName) < File xmlFile = new File(fileName); JAXBContext jaxbContext; try < jaxbContext = JAXBContext.newInstance(Employee.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Employee employee = (Employee) jaxbUnmarshaller.unmarshal(xmlFile); System.out.println(employee); >catch (JAXBException e) < e.printStackTrace(); >>
Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]

Drop me your questions in comments section.

Источник

How to convert a Java object to XML using JAXB

Java Architecture for XML Binding (JAXB) is a popular choice for mapping Java objects to and from XML. It provides an easy-to-use programming interface for reading and writing Java objects to XML and vice versa.

Читайте также:  Find words in text python

In this guide, you’ll learn how to transform a Java object into an XML document. We’ll also look at an example of converting an XML document back to a Java object.

JAXB is a part of the Java Development Kit (JDK) since Java 1.6. So you don’t need any 3rd-party dependency to use JAXB in your project.

In JAXB terminology, Java object to XML conversion is referred to as marshalling. Marshalling is a process of converting a Java object to an XML document. JAXB provides the Marshall class to perform this conversion.

Before we discuss how marshaling works, let us first create two simple Java classes called Author and Book . These classes model a basic scenario where we have books, and each book has just one author. We start by creating the Author class to model the author: Author.java

public class Author  private Long id; private String firstName; private String lastName; public Author()  > public Author(Long id, String firstName, String lastName)  this.id = id; this.firstName = firstName; this.lastName = lastName; > public Long getId()  return id; > public void setId(Long id)  this.id = id; > public String getFirstName()  return firstName; > public void setFirstName(String firstName)  this.firstName = firstName; > public String getLastName()  return lastName; > public void setLastName(String lastName)  this.lastName = lastName; > @Override public String toString()  return "Author + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '>'; > > 

The Author is a simple Java class with an ID, first and last names, with corresponding getting and setter methods. Next, we will create the Book class and annotate its fields with JAXB annotations to control how it should be marshalled to XML: Book.java

@XmlRootElement(name = "book") public class Book  private Long id; private String title; private String isbn; private Author author; public Book()  > public Book(Long id, String title, String isbn, Author author)  this.id = id; this.title = title; this.isbn = isbn; this.author = author; > public Long getId()  return id; > @XmlAttribute(name = "id") public void setId(Long id)  this.id = id; > public String getTitle()  return title; > @XmlElement(name = "title") public void setTitle(String title)  this.title = title; > public String getIsbn()  return isbn; > public void setIsbn(String isbn)  this.isbn = isbn; > public Author getAuthor()  return author; > @XmlElement(name = "author") public void setAuthor(Author author)  this.author = author; > @Override public String toString()  return "Book + "id=" + id + ", title='" + title + '\'' + ", isbn='" + isbn + '\'' + ", author=" + author + '>'; > > 
  • @XmlRootElement — This annotation is used at the top-level class to specify the root element of the XML document. The name attribute in the annotation is optional. If not specified, the class name is used as the root element name in the XML document.
  • @XmlAttribute — This annotation is used to indicate the attribute of the root element.
  • @XmlElement — This annotation is used on the fields of the class that will be the sub-elements of the root element.

That’s it. The Book class is now ready to be marshaled into an XML document. Let us start with a simple scenario where you want to convert a Java Object to an XML string.

To convert a Java object to an XML string, you first create an instance of JAXBContext . This is the entry point to JAXB API that provides several methods to marshal, unmarshal, and validate XML documents. Next, get the Marshall instance from JAXBContext . Afterward, use its marshal() method to marshall a Java object to XML. You can write the generated XML to a file, or a string, or print it on the console. Here is an example that converts a Book object to an XML string:

try  // create an instance of `JAXBContext` JAXBContext context = JAXBContext.newInstance(Book.class); // create an instance of `Marshaller` Marshaller marshaller = context.createMarshaller(); // enable pretty-print XML output marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // write XML to `StringWriter` StringWriter sw = new StringWriter(); // create a `Book` object Book book = new Book(17L, "Head First Java", "ISBN-45565-45", new Author(5L, "Bert", "Bates")); // convert book object to XML marshaller.marshal(book, sw); // print the XML System.out.println(sw.toString()); > catch (JAXBException ex)  ex.printStackTrace(); > 
 book id="17"> author> firstName>BertfirstName> id>5id> lastName>BateslastName> author> isbn>ISBN-45565-45isbn> title>Head First Javatitle> book> 

Java object to an XML file conversion is similar to the above example. All you need to do is replace the StringWriter instance with an instance of File where you want to store the XML:

try  // create an instance of `JAXBContext` JAXBContext context = JAXBContext.newInstance(Book.class); // create an instance of `Marshaller` Marshaller marshaller = context.createMarshaller(); // enable pretty-print XML output marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // create an XML file File file = new File("book.xml"); // create a `Book` object Book book = new Book(17L, "Head First Java", "ISBN-45565-45", new Author(5L, "Bert", "Bates")); // convert book object to XML file marshaller.marshal(book, file); > catch (JAXBException ex)  ex.printStackTrace(); > 

If you execute the above code snippet, you should see an XML file called book.xml generated with the same XML content as we have seen in the above example.

XML to Java object conversion or unmarshalling involves creating an instance of Unmarshaller from the JAXBContext and calling the unmarshal() method. This method accepts the XML file as an argument to unmarshal. The following example shows how you can convert the book.xml file, we just created, into an instance of Book :

try  // create an instance of `JAXBContext` JAXBContext context = JAXBContext.newInstance(Book.class); // create an instance of `Unmarshaller` Unmarshaller unmarshaller = context.createUnmarshaller(); // XML file path File file = new File("book.xml"); // convert an XML file to a `Book` object Book book = (Book) unmarshaller.unmarshal(file); // print book object System.out.println(book); > catch (JAXBException ex)  ex.printStackTrace(); > 
Bookid=17, title='Head First Java', isbn='ISBN-45565-45', author=Authorid=5, firstName='Bert', lastName='Bates'>> 

Sometimes, you want to marshal Java collection objects such as List , Map , or Set to an XML document and convert XML back to Java collection objects. For such a scenario, we need to create a special class named Books that holds a List of Book objects. Here is what it looks like: Books.java

@XmlRootElement(name = "books") public class Books  private ListBook> books; public ListBook> getBooks()  return books; > @XmlElement(name = "book") public void setBooks(ListBook> books)  this.books = books; > public void add(Book book)  if (this.books == null)  this.books = new ArrayList>(); > this.books.add(book); > > 

In the Books class above, the @XmlRootElement annotation indicates the root element of the XML as books . This class has a single List field with getter and setter methods. The add() method of this class accepts a Book object and adds it to the list. The following example demonstrates how you can convert a Java collection object into an XML document:

try  // create an instance of `JAXBContext` JAXBContext context = JAXBContext.newInstance(Books.class); // create an instance of `Marshaller` Marshaller marshaller = context.createMarshaller(); // enable pretty-print XML output marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // create a `Books` object Books books = new Books(); // add books to list books.add(new Book(1L, "Head First Java", "ISBN-45565-45", new Author(1L, "Bert", "Bates"))); books.add(new Book(2L, "Thinking in Java", "ISBN-95855-3", new Author(2L, "Bruce", "Eckel"))); // convert `Books` object to XML file marshaller.marshal(books, new File("books.xml")); // print XML to console marshaller.marshal(books, System.out); > catch (JAXBException ex)  ex.printStackTrace(); > 
 books> book id="1"> author> firstName>BertfirstName> id>1id> lastName>BateslastName> author> isbn>ISBN-45565-45isbn> title>Head First Javatitle> book> book id="2"> author> firstName>BrucefirstName> id>2id> lastName>EckellastName> author> isbn>ISBN-95855-3isbn> title>Thinking in Javatitle> book> books> 

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Оцените статью