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

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

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Migrate Serialized Java Objects with XStream and XMT
  • What Is Ant, Really?
  • How to Convert JSON to XML or XML to JSON in Java
  • How to Convert CSV to XML in Java

Trending

  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • From Fragmentation to Focus: A Data-First, Team-First Framework for Platform-Driven Organizations
  • Transforming AI-Driven Data Analytics with DeepSeek: A New Era of Intelligent Insights
  • How To Replicate Oracle Data to BigQuery With Google Cloud Datastream
  1. DZone
  2. Coding
  3. Languages
  4. Convert Java Objects to XML and XML to Java Objects with XStream

Convert Java Objects to XML and XML to Java Objects with XStream

Learn how to convert XML objects to Java, and vice versa.

By 
Hari Subramanian user avatar
Hari Subramanian
·
Feb. 04, 14 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
124.2K Views

Join the DZone community and get the full member experience.

Join For Free

Once I got to deal with an incident where I had to load a lot of data (20 MB+) from the DB and populate it as java object (the java object is of many nested / referenced classes), and I needed to load that every time I started my server. Though we have a distributed cache in place, subsequent loads would be very fast. However, the first time load was taking more than 9 minutes...

I was thinking that rather than loading from the DB on server restart, I could load from the local file!! (as the data in the db updates less often) that's where I got to learn about the XStream Library, and it's so simple that I could convert any java object to XML and back.

Here I will show you how easy it is to use the XStream library

First let's create a Sample Object (you can use any existing class as well) as follows

SampleObject.java

public class SampleObject {  
     private String name="Test";  
     private int testInt ;  
     public String getName() {  
         return name;  
     }  
     public void setName(String name) {  
         this.name = name;  
     }  
   public int getTestInt() {  
         return testInt;  
     }  
     public void setTestInt(int testInt) {  
         this.testInt = testInt;  
     }  
 }  

and a helper class for conversion XStreamTranslator.java

 import java.io.File;  
 import java.io.FileReader;  
 import java.io.FileWriter;  
 import java.io.IOException;  
 import java.util.Iterator;  
 import java.util.List;  
 import com.thoughtworks.xstream.XStream;  

 public final class XStreamTranslator {  
     private XStream xstream = null;  
     private XStreamTranslator(){  
         xstream = new XStream();  
         xstream.ignoreUnknownElements();  
}  
     /**  
      * Convert a any given Object to a XML String  
      * @param object  
      * @return  
      */  
     public String toXMLString(Object object) {  
         return xstream.toXML(object);   
     }  
     /**  
      * Convert given XML to an Object  
      * @param xml  
      * @return  
      */  
     public Object toObject(String xml) {  
         return (Object) xstream.fromXML(xml);  
     }  
     /**  
      * return this class instance  
      * @return  
      */  
     public static XStreamTranslator getInstance(){  
         return new XStreamTranslator();  
     }  
     /**  
      * convert to Object from given File   
      * @param xmlFile  
      * @return  
      * @throws IOException   
      */  
     public Object toObject(File xmlFile) throws IOException {  
         return xstream.fromXML(new FileReader(xmlFile));  
     }  
     /**  
      * create XML file from the given object with custom file name  
      * @param fileName   
      * @param file  
      * @throws IOException   
      */  
     public void toXMLFile(Object objTobeXMLTranslated, String fileName ) throws IOException {  
         FileWriter writer = new FileWriter(fileName);  
         xstream.toXML(objTobeXMLTranslated, writer);  
         writer.close();  
     }  
     public void toXMLFile(Object objTobeXMLTranslated, String fileName, List omitFieldsRegXList) throws IOException {  
         xstreamInitializeSettings(objTobeXMLTranslated, omitFieldsRegXList);  
         toXMLFile(objTobeXMLTranslated, fileName);      
     }      
     /**  
      * @  
      * @param objTobeXMLTranslated  
      */  
     public void xstreamInitializeSettings(Object objTobeXMLTranslated, List omitFieldsRegXList) {  
         if(omitFieldsRegXList != null && omitFieldsRegXList.size() > 0){  
             Iterator itr = omitFieldsRegXList.iterator();  
             while(itr.hasNext()){  
                 String omitEx = itr.next();  
                 xstream.omitField(objTobeXMLTranslated.getClass(), omitEx);  
             }  
         }   
     }  
     /**  
      * create XML file from the given object, file name is generated automatically (class name)  
      * @param objTobeXMLTranslated  
      * @throws IOException  
      * @throws XStreamTranslateException   
      */  
     public void toXMLFile(Object objTobeXMLTranslated) throws IOException {  
         toXMLFile(objTobeXMLTranslated,objTobeXMLTranslated.getClass().getName()+".xml");  
     }  
 }

few Test cases to verify

import static org.junit.Assert.assertEquals;  
 import static org.junit.Assert.assertNotNull;  
 import static org.junit.Assert.assertTrue;  
 import java.io.File;  
 import java.io.IOException;  
 import java.util.ArrayList;  
 import java.util.List;  
 import org.apache.commons.io.FileUtils;  
 import org.junit.After;  
 import org.junit.Before;  
 import org.junit.Test;  

 public class XStreamTranslatorTest {  
     SampleObject sampleObj;  
     XStreamTranslator xStreamTranslatorInst;  
     /**  
      * @throws java.lang.Exception  
      */  
     @Before  
     public void setUp() throws Exception {  
         sampleObj = new SampleObject();  
         xStreamTranslatorInst = XStreamTranslator.getInstance();  
     }  
     /**  
      * @throws java.lang.Exception  
      */  
     @After  
     public void tearDown() throws Exception {  
     }  
     @Test  
     public void simpleObjectToXMLStringNotNullTest() {  
         String xml = xStreamTranslatorInst.toXMLString(sampleObj);  
         assertNotNull(xml);  
     }  
     @Test  
     public void simpleObjectToXMLStringVerifyTest() {  
         sampleObj.setName("Test");  
         assertEquals("Test",sampleObj.getName());  
         sampleObj.setTestInt(9);  
         assertEquals(9,sampleObj.getTestInt());  
         String xml = xStreamTranslatorInst.toXMLString(sampleObj);  
         String expected = getExpectedStringOutOfSampleObject();  
         assertEquals(expected, xml.replaceAll("[\\n\\s\\t]+", ""));  
     }  
     @Test   
     public void xmlToObjectVerifyTest(){  
         String xml = getExpectedStringOutOfSampleObject();  
         SampleObject sampleObj = (SampleObject) xStreamTranslatorInst.toObject(xml);  
         assertNotNull(sampleObj);  
     }  
     @Test (expected=IOException.class)  
     public void xmlToAnyObjectFromFileThatNotExists() throws IOException{  
         SampleObject sampleObj = (SampleObject) xStreamTranslatorInst.toObject(new File("C:\\MyHome\\mySampleCodes\\xstream-samples\\src\\test\\resources\\testNoFile.xml"));  
         assertNotNull(sampleObj);  
         assertEquals("somename",sampleObj.getName());  
     }  
     @Test   
     public void xmlToAnyObjectFromFile() throws IOException{  
         SampleObject sampleObj = (SampleObject) xStreamTranslatorInst.toObject(new File("C:\\MyHome\\mySampleCodes\\xstream-samples\\src\\test\\resources\\testSampleObject.xml"));  
         assertNotNull(sampleObj);  
         assertEquals("Test",sampleObj.getName());  
     }      
     @Test   
     public void objToXmlFileTestForNotNull() throws IOException {  
         SampleObject sampleObj = new SampleObject();  
         sampleObj.setName("Test2");  
         assertEquals("Test2",sampleObj.getName());  
         sampleObj.setTestInt(99);  
         assertEquals(99,sampleObj.getTestInt());  
         xStreamTranslatorInst.toXMLFile(sampleObj);  
         File file = new File(sampleObj.getClass().getName()+".xml");  
         assertTrue(file.exists());  
         String sample = FileUtils.readFileToString(file);  
         assertNotNull(sample);  
     }      
     @Test   
     public void objToXmlFileCreate() throws IOException {  
         SampleObject sampleObj = new SampleObject();  
         sampleObj.setName("Test2");  
         assertEquals("Test2",sampleObj.getName());  
         sampleObj.setTestInt(99);  
         assertEquals(99,sampleObj.getTestInt());  
         xStreamTranslatorInst.toXMLFile(sampleObj);  
         File file = new File(sampleObj.getClass().getName()+".xml");  
         assertTrue(file.exists());  
         String sample = FileUtils.readFileToString(file);  
         assertNotNull(sample);  
         assertEquals(getExpectedStringOutOfSampleObject2(),sample.replaceAll("[\\n\\s\\t]+", ""));  
     }  
     private String getExpectedStringOutOfSampleObject() {  
         return "<com.mysamples.thoughtworks.xstream.SampleObject><name>Test</name><testInt>9</testInt></com.mysamples.thoughtworks.xstream.SampleObject>";  
     }  
     private String getExpectedStringOutOfSampleObject2() {  
         return "<com.mysamples.thoughtworks.xstream.SampleObject><name>Test2</name><testInt>99</testInt></com.mysamples.thoughtworks.xstream.SampleObject>";  
     }      
 }  

Add the following dependency in your pom.xml (dependencies section)

<dependency>   
   <groupId>com.thoughtworks.xstream</groupId>   
   <artifactId>xstream</artifactId>   
   <version>1.4.5</version>   
</dependency>   

Run your test cases and see for yourself how the xml got generated from the sample object and back to SampleObject.

following is the sample xml that I have..

<com.mysamples.thoughtworks.xstream.SampleObject>   
  <name>Test2</name>   
  <testInt>99</testInt>   
</com.mysamples.thoughtworks.xstream.SampleObject>   


XML Object (computer science) Java (programming language) XStream Convert (command)

Opinions expressed by DZone contributors are their own.

Related

  • Migrate Serialized Java Objects with XStream and XMT
  • What Is Ant, Really?
  • How to Convert JSON to XML or XML to JSON in Java
  • How to Convert CSV to XML 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!