Java convert xml to objects

Java Guides

Java Architecture for XML Binding (JAXB) is a Java standard that allows Java developers to map Java classes to XML representations. JAXB enables to marshal Java objects into XML and unmarshal XML back into Java objects.

Marshalling is the process of transforming Java objects into XML documents.
Unmarshalling is the process of reading XML documents into Java objects.

In Java 9, JAXB has moved into a separate module java.xml. In Java 9 and Java 10 we need to use the —add-modules=java.xml.bind option. In Java 11, JAXB has been removed from JDK and we need to add it to the project as a separate library via Maven or Gradle.

Video Tutorial

Development Steps

1. Create a Simple Maven Project

2. Add Maven Dependencies

project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> modelVersion>4.0.0modelVersion> groupId>net.javaguides.xmlgroupId> artifactId>java-xml-tutorialartifactId> version>0.0.1-SNAPSHOTversion> dependencies> dependency> groupId>javax.xml.bindgroupId> artifactId>jaxb-apiartifactId> version>2.2.11version> dependency> dependency> groupId>com.sun.xml.bindgroupId> artifactId>jaxb-coreartifactId> version>2.2.11version> dependency> dependency> groupId>com.sun.xml.bindgroupId> artifactId>jaxb-implartifactId> version>2.2.11version> dependency> dependency> groupId>javax.activationgroupId> artifactId>activationartifactId> version>1.1.1version> dependency> dependencies> build> sourceDirectory>src/main/javasourceDirectory> plugins> plugin> artifactId>maven-compiler-pluginartifactId> version>3.5.1version> configuration> source>1.8source> target>1.8target> configuration> plugin> plugins> build> project>

3. Create POJO classes and Add JAXB annotations

  1. @XmlRootElement : This is a must-have an annotation for the Object to be used in JAXB. It defines the root element for the XML content.
  2. @XmlType : It maps the class to the XML schema type. We can use it for ordering the elements in the XML.
  3. @XmlTransient : This will make sure that the Object property is not written to the XML.
  4. @XmlAttribute : This will create the Object property as an attribute.
  5. @XmlElement(name = “ABC”) : This will create the element with name “ABC”
Читайте также:  Python numpy count nonzero

3.1 Book POJO Class

package net.javaguides.javaxmlparser.jaxb; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "book") @XmlType(propOrder = < "author", "name", "publisher", "isbn" >) public class Book < private String name; private String author; private String publisher; private String isbn; @XmlElement(name = "title") public String getName() < return name; > public void setName(String name) < this.name = name; > public String getAuthor() < return author; > public void setAuthor(String author) < this.author = author; > public String getPublisher() < return publisher; > public void setPublisher(String publisher) < this.publisher = publisher; > public String getIsbn() < return isbn; > public void setIsbn(String isbn) < this.isbn = isbn; > >

3.2 Bookstore POJO Class

package net.javaguides.javaxmlparser.jaxb; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(namespace = "net.javaguides.javaxmlparser.jaxb") public class Bookstore < @XmlElementWrapper(name = "bookList") @XmlElement(name = "book") private List  Book > bookList; private String name; private String location; public void setBookList(List < Book > bookList) < this.bookList = bookList; > public List < Book > getBooksList() < return bookList; > public String getName() < return name; > public void setName(String name) < this.name = name; > public String getLocation() < return location; > public void setLocation(String location) < this.location = location; > >

4. Convert Java Object to an XML

package net.javaguides.javaxmlparser.jaxb; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; /** * Marshaller Class - Convert Java Object to XML * * @author Ramesh Fadatare * */ public class BookMain < private static final String BOOKSTORE_XML = "bookstore-jaxb.xml"; public static void main(String[] args) throws JAXBException, IOException < List  Book > bookList = new ArrayList < Book > (); // create books Book book1 = new Book(); book1.setIsbn("978-0134685991"); book1.setName("Effective Java"); book1.setAuthor("Joshua Bloch"); book1.setPublisher("Amazon"); bookList.add(book1); Book book2 = new Book(); book2.setIsbn("978-0596009205"); book2.setName("Head First Java, 2nd Edition"); book2.setAuthor("Kathy Sierra"); book2.setPublisher("amazon"); bookList.add(book2); // create bookstore, assigning book Bookstore bookstore = new Bookstore(); bookstore.setName("Amazon Bookstore"); bookstore.setLocation("Newyorkt"); bookstore.setBookList(bookList); convertObjectToXML(bookstore); > private static void convertObjectToXML(Bookstore bookstore) throws JAXBException, FileNotFoundException < // create JAXB context and instantiate marshaller JAXBContext context = JAXBContext.newInstance(Bookstore.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to System.out m.marshal(bookstore, System.out); // Write to File m.marshal(bookstore, new File(BOOKSTORE_XML)); > >

The above program creates a file named bookstore-jaxb.xml and stored Book objects into this XML file:

xml version="1.0" encoding="UTF-8" standalone="yes"?> ns2:bookstore xmlns:ns2="net.javaguides.javaxmlparser.jaxb"> bookList> book> author>Joshua Blochauthor> title>Effective Javatitle> publisher>Amazonpublisher> isbn>978-0134685991isbn> book> book> author>Kathy Sierraauthor> title>Head First Java, 2nd Editiontitle> publisher>amazonpublisher> isbn>978-0596009205isbn> book> bookList> location>Newyorktlocation> name>Amazon Bookstorename> ns2:bookstore>

5. Convert XML to Java Object

Let’s convert the XML document that was generated in the above example to Java object.

Let’s convert a bookstore-jaxb.xml document into Java Object:

package net.javaguides.javaxmlparser.jaxb; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; /** * Unmarshaller Class - Convert XML to Object in Java * @author Ramesh Fadatare * */ public class BookMain < private static final String BOOKSTORE_XML = "bookstore-jaxb.xml"; public static void main(String[] args) throws JAXBException, IOException < convertXMLToObject(); >private static Bookstore convertXMLToObject() < try < JAXBContext context = JAXBContext.newInstance(Bookstore.class); Unmarshaller un = context.createUnmarshaller(); Bookstore bookstore = (Bookstore) un.unmarshal(new File(BOOKSTORE_XML)); List  Book > list = bookstore.getBooksList(); for (Book book: list) < System.out.println("Book: " + book.getName() + " from " + book.getAuthor()); > > catch (JAXBException e) < e.printStackTrace(); > return null; > >
Book: Effective Java from Joshua Bloch Book: Head First Java, 2nd Edition from Kathy Sierra

Conclusion

In this tutorial, we have seen how to use JAXB API to convert Java object to/from XML. In this tutorial, we have used Java 11 to develop and run the examples.

Источник

Converting XML data to Object in Java

In this blog, we will explore the process of converting XML data into Java objects using three popular techniques: JAXB, DOM Parser, and Jackson XML.

Introduction:

Handling XML data in Java applications often requires converting it into Java objects for easy manipulation and processing. In this blog, we will explore three powerful techniques for XML to object conversion: JAXB, DOM Parser, and Jackson XML. Through practical examples and step-by-step explanations, you will learn how to efficiently convert XML data into Java objects. So let’s dive in and master the art of XML to object conversion in Java.

Method 1: Using JAXB (Java Architecture for XML Binding)

JAXB provides a convenient way to map XML elements and attributes to Java classes. To illustrate this technique, consider the following example:

import javax.xml.bind.annotation.*; @XmlRootElement(name = "book") public class Book < @XmlElement private String title; @XmlElement private String author; // Getters and setters >// Perform XML to object conversion using JAXB import javax.xml.bind.*; public class JAXBExample < public static void main(String[] args) throws JAXBException < JAXBContext jaxbContext = JAXBContext.newInstance(Book.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Book book = (Book) unmarshaller.unmarshal(new File("book.xml")); System.out.println("Title: " + book.getTitle()); System.out.println("Author: " + book.getAuthor()); >> 

Output:

Title: The Great Gatsby Author: F. Scott Fitzgerald 

Method 2: Using DOM Parser

The DOM Parser allows manual parsing and mapping of XML elements to Java objects. Let’s see an example that demonstrates this approach:

import org.w3c.dom.*; import javax.xml.parsers.*; import java.io.*; public class DOMParserExample < public static void main(String[] args) throws Exception < DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("book.xml")); NodeList bookNodes = document.getElementsByTagName("book"); for (int i = 0; i < bookNodes.getLength(); i++) < Element bookElement = (Element) bookNodes.item(i); String title = bookElement.getElementsByTagName("title").item(0).getTextContent(); String author = bookElement.getElementsByTagName("author").item(0).getTextContent(); System.out.println("Title: " + title); System.out.println("Author: " + author); >> > 

Output:

Title: The Great Gatsby Author: F. Scott Fitzgerald 

Method 3: Using Jackson XML

Jackson XML provides powerful data-binding capabilities for XML in Java. Consider the following example:

import com.fasterxml.jackson.dataformat.xml.*; public class JacksonXMLExample < public static void main(String[] args) throws Exception < XmlMapper xmlMapper = new XmlMapper(); Book book = xmlMapper.readValue(new File("book.xml"), Book.class); System.out.println("Title: " + book.getTitle()); System.out.println("Author: " + book.getAuthor()); >> 

Output:

Title: The Great Gatsby Author: F. Scott Fitzgerald 

Conclusion:

In this blog, we explored three popular techniques for XML to object conversion in Java. We learned about JAXB, which provides a declarative approach for mapping XML elements to Java classes. Additionally, we explored the DOM Parser technique for manual parsing and object creation. Lastly, we discovered the power of Jackson XML for XML data-binding in Java.

Related Post

Источник

UnMarshalling- How to convert XML to Java Objects using JAXB

This tutorial explains how to use JAXB (Java Architecture for XML Binding) to convert an XML document to Java Objects.

The previous tutorial has explained the conversion of Java Objects to XML.

As of Java 11, JAXB is not part of the JRE anymore, and you need to configure the relevant libraries via your dependency management system, for example, either Maven or Gradle.

Configure the Java compiler level to be at least 11 and add the JAXB dependencies to your pom file.

  4.0.0 org.example JAXBDemo 0.0.1-SNAPSHOT JAXBDemo http://www.example.com UTF-8 11 11   junit junit 4.13.2 test  com.sun.xml.bind jaxb-impl 2.3.3    

Sample XML Structure

  Terry Mathew female 30 married Manager +919999988822 abc@test.com 75000.0  

Un-marshalling provides a client application the ability to convert XML data into JAXB-derived Java objects.

Let’s see the steps to convert XML document into java object.

  1. Create POJO Class
  2. Create the JAXBContext object
  3. Create the Unmarshaller objects
  4. Call the unmarshal method
  5. Use getter methods of POJO to access the data

Now, let us create the Java Objects (POJO) for the above XML.

import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "EmployeeDetails") @XmlAccessorType(XmlAccessType.FIELD) //Define the order in which the fields are written in XML @XmlType(propOrder = < "firstName", "lastName", "gender", "age", "maritalStatus", "designation", "contactNumber","emailId", "salary" >) public class Employee < private String firstName; private String lastName; private int age; @XmlElement(name = "GrossSalary") private double salary; private String designation; private String contactNumber; private String emailId; private String gender; private String maritalStatus; public Employee() < super(); >// Getter and setter methods 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; >public int getAge() < return age; >public void setAge(int age) < this.age = age; >public double getSalary() < return salary; >public void setSalary(double salary) < this.salary = salary; >public String getDesignation() < return designation; >public void setDesignation(String designation) < this.designation = designation; >public String getContactNumber() < return contactNumber; >public void setContactNumber(String contactNumber) < this.contactNumber = contactNumber; >public String getEmailId() < return emailId; >public void setEmailId(String emailId) < this.emailId = emailId; >public String getGender() < return gender; >public void setGender(String gender) < this.gender = gender; >public String getMaritalStatus() < return maritalStatus; >public void setMaritalStatus(String maritalStatus) < this.maritalStatus = maritalStatus; >@Override public String toString() < return "Employee [FirstName=" + firstName + ", LastName=" + lastName + ", Age=" + age + ", Salary=" + salary + ", Designation=" + designation + ", ContactNumber=" + contactNumber + ", EmailId=" + emailId + ", Gender=" + gender + ", MaritalStatus=" + maritalStatus + "]"; >>

Create the following test program for reading the XML file. The XML file is present under src/test/resources.

Let’s use JAXB Unmarshaller to unmarshal our JAXB_XML back to a Java object:

import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.junit.Test; public class JAXBDeserialization < @Test public void JAXBUnmarshalTest() < try < String userDir = System.getProperty("user.dir"); File file = new File(userDir + "\\src\\test\\resources\\JAXB_XML.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Employee employee = (Employee) jaxbUnmarshaller.unmarshal(file); System.out.println("FirstName: " + employee.getFirstName()); System.out.println("LastName: " + employee.getLastName()); System.out.println("Age: " + employee.getAge()); System.out.println("Salary: " + employee.getSalary()); System.out.println("Contact Number: " + employee.getContactNumber()); System.out.println("Designation: " + employee.getDesignation()); System.out.println("Gender: " + employee.getGender()); System.out.println("EmailId: " + employee.getEmailId()); System.out.println("MaritalStatus: " + employee.getMaritalStatus()); >catch (JAXBException e) < e.printStackTrace(); >> >

When we run the code above, we may check the console output to verify that we have successfully converted XML data into a Java object:

The output of the above program is

There is another simple way of unmarshalling the XML to Java Objects.

@Test public void JAXBUnmarshalTest1() < try < String userDir = System.getProperty("user.dir"); File file = new File(userDir + "\\src\\test\\resources\\JAXB_XML.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Employee emp = (Employee) jaxbUnmarshaller.unmarshal(file); System.out.println(emp); >catch (JAXBException e) < e.printStackTrace(); >>

When we run the code above, we may check the console output to verify that we have successfully converted XML data into a Java object:

The output of the above program is

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Источник

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