DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Migrate Serialized Java Objects with XStream and XMT
  • What Is Ant, Really?
  • Using the Chain of Responsibility Design Pattern in Java
  • How to Convert XLS to XLSX in Java

Trending

  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • Ensuring Configuration Consistency Across Global Data Centers
  • AI-Based Threat Detection in Cloud Security
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  1. DZone
  2. Coding
  3. Languages
  4. Using JAXB to Generate Java Objects from XML Document

Using JAXB to Generate Java Objects from XML Document

By 
Mohamed Sanaulla user avatar
Mohamed Sanaulla
·
Jan. 29, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
169.4K Views

Join the DZone community and get the full member experience.

Join For Free

Quite sometime back I had written about Using JAXB to generate XML from the Java, XSD. And now I am writing how to do the reverse of it i.e generating Java objects from the XML document. There was one comment mentioning that JAXB reference implementation and hence in this article I am making use of the reference implementation that is shipped with the JDK.

Firstly the XML which I am using to generate the java objects are:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<expenseReport>
  <user>
    <userName>Sanaulla</userName>
  </user>
  <items>
    <item>
      <itemName>Seagate External HDD</itemName>
      <purchasedOn>August 24, 2010</purchasedOn>
      <amount>6776.5</amount>
    </item>
    <item>
      <itemName>Benq HD Monitor</itemName>
      <purchasedOn>August 24, 2012</purchasedOn>
      <amount>15000</amount>
    </item>
  </items>
</expenseReport>

And the XSD to which it conforms to is:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="expenseReport" type="ExpenseT" />
  <xs:complexType name="ExpenseT">
    <xs:sequence>
      <xs:element name="user" type="UserT" />
      <xs:element name="items" type="ItemListT" />
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="UserT">
    <xs:sequence>
      <xs:element name="userName" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="ItemListT">
    <xs:sequence>
      <xs:element name="item" type="ItemT" maxOccurs="unbounded" />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="ItemT">
    <xs:sequence>
      <xs:element name="itemName" type="xs:string" />
      <xs:element name="purchasedOn" type="xs:string" />
      <xs:element name="amount" type="xs:decimal" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>

The XSD has already been explained and one can find out more by reading this article.

I create a class: XmlToJavaObjects which will drive the unmarshalling operation and before I generate the JAXB Classes from the XSD, the directory structure is:
DirStruct

I go ahead and use the xjc.exe to generate JAXB classes for the given XSD:

$> xjc expense.xsd

and I now refresh the directory structure to see these generated classes as shown below:
DirStruct2
With the JAXB Classes generated and the XML data available, we can go ahead with the Unmarshalling process.

Unmarshalling the XML:

To unmarshall:

  1. We need to create JAXContext instance.
  2. Use JAXBContext instance to create the Unmarshaller.
  3. Use the Unmarshaller to unmarshal the XML document to get an instance of JAXBElement.
  4. Get the instance of the required JAXB Root Class from the JAXBElement.

Once we get the instance of the required JAXB Root class, we can use it to get the complete XML data in Java objects. The code to unmarshal the XML data is given below:

package problem;

import generated.ExpenseT;
import generated.ItemListT;
import generated.ItemT;
import generated.ObjectFactory;
import generated.UserT;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class XmlToJavaObjects {

  /**
   * @param args
   * @throws JAXBException 
   */
  public static void main(String[] args) throws JAXBException {
    //1. We need to create JAXContext instance
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);

    //2. Use JAXBContext instance to create the Unmarshaller.
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    //3. Use the Unmarshaller to unmarshal the XML document to get an instance of JAXBElement.
    JAXBElement<ExpenseT> unmarshalledObject = 
        (JAXBElement<ExpenseT>)unmarshaller.unmarshal(
            ClassLoader.getSystemResourceAsStream("problem/expense.xml"));

    //4. Get the instance of the required JAXB Root Class from the JAXBElement.
    ExpenseT expenseObj = unmarshalledObject.getValue();
    UserT user = expenseObj.getUser();
    ItemListT items = expenseObj.getItems();

    //Obtaining all the required data from the JAXB Root class instance.
    System.out.println("Printing the Expense for: "+user.getUserName());
    for ( ItemT item : items.getItem()){
      System.out.println("Name: "+item.getItemName());
      System.out.println("Value: "+item.getAmount());
      System.out.println("Date of Purchase: "+item.getPurchasedOn());
    }   
  }

}

And the output would be:
Output

Do drop in your queries/feedback as comments and I will try to address them at the earliest.



XML Java (programming language) Object (computer science) code style

Published at DZone with permission of Mohamed Sanaulla, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Migrate Serialized Java Objects with XStream and XMT
  • What Is Ant, Really?
  • Using the Chain of Responsibility Design Pattern in Java
  • How to Convert XLS to XLSX in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!