Visit Sponsor

Written by 1:13 pm Android

Android POJO to XML Conversion – Library Examples and Best Practices

In Android apps, converting Java objects (POJOs) to XML is a common requirement for data exchange, persistence, configuration, or interfacing with legacy systems and web services. While JSON is more prevalent today, XML remains essential in many domains such as SOAP web services, RSS feeds, and custom serialization formats.

This guide explains how to convert a POJO to XML in Android using multiple approaches with concrete examples and best practices.

What Is a POJO?

A POJO (Plain Old Java Object) is a simple Java class without special restrictions or frameworks. It contains fields, getters, setters, and sometimes domain logic. A typical POJO looks like:

public class User {
    private String name;
    private int age;
    private String email;

    // Getters and setters
}

To convert this object to XML, you need a serializer that understands how to map class fields to XML elements and attributes.

Approaches for Converting POJOs to XML in Android

MethodSuitable ForNotes
Simple XML FrameworkFull object graph XMLEasy mapping, widely used
XmlSerializer (Android built-in)Lightweight manual controlNo annotations
JAXB (Java XML Binding)Strong bindingNot included in Android SDK (alternate libs required)

We cover each approach below.

Using Simple XML Framework

Simple XML is a lightweight XML serialization library that uses annotations on POJOs to control how fields serialize to XML.

Add Dependency

In app/build.gradle:

dependencies {
    implementation 'org.simpleframework:simple-xml:2.7.1'
}

Annotate Your POJO

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name = "User")
public class User {

    @Element(name = "Name")
    private String name;

    @Element(name = "Age")
    private int age;

    @Element(name = "Email")
    private String email;

    public User() {} // Required for serialization

    // Getters and setters...
}

Serialize POJO to XML

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

User user = new User("Alice", 30, "alice@example.com");

Serializer serializer = new Persister();
StringWriter writer = new StringWriter();

try {
    serializer.write(user, writer);
    String xml = writer.toString();
    Log.d("XML", xml);
} catch (Exception e) {
    e.printStackTrace();
}

Output Example:

<User>
   <Name>Alice</Name>
   <Age>30</Age>
   <Email>alice@example.com</Email>
</User>

This method is clean, annotation-driven, and ideal for complex object hierarchies.

Using Android XmlSerializer (Built-in)

XmlSerializer is part of the Android SDK and allows manual building of XML without external libraries. It doesn’t use annotations; you manually write tags.

Serialize Example

import android.util.Xml;

User user = new User("Bob", 25, "bob@example.com");

XmlSerializer xmlSerializer = Xml.newSerializer();
StringWriter writer = new StringWriter();

try {
    xmlSerializer.setOutput(writer);
    xmlSerializer.startDocument("UTF-8", true);
    xmlSerializer.startTag(null, "User");

    xmlSerializer.startTag(null, "Name");
    xmlSerializer.text(user.getName());
    xmlSerializer.endTag(null, "Name");

    xmlSerializer.startTag(null, "Age");
    xmlSerializer.text(String.valueOf(user.getAge()));
    xmlSerializer.endTag(null, "Age");

    xmlSerializer.startTag(null, "Email");
    xmlSerializer.text(user.getEmail());
    xmlSerializer.endTag(null, "Email");

    xmlSerializer.endTag(null, "User");
    xmlSerializer.endDocument();

    String xml = writer.toString();
    Log.d("XML", xml);

} catch (Exception e) {
    e.printStackTrace();
}

Output XML:

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<User>
    <Name>Bob</Name>
    <Age>25</Age>
    <Email>bob@example.com</Email>
</User>

This approach gives full control but requires more manual XML building.

JAXB-Style Binding Libraries (Alternative)

Java EE’s JAXB (Java Architecture for XML Binding) is a standard binding framework for converting Java objects to XML. It uses annotations like @XmlRootElement, @XmlElement, etc.

Android’s default SDK does not include JAXB. However, you can use alternative libraries or include a JAXB implementation manually. In practice, for Android projects with heavy XML usage, Simple XML is preferred over JAXB due to smaller footprint and Android compatibility.

Handling Nested Objects and Lists

If your POJO contains nested objects or collections, annotation-driven serializers handle it smoothly.

Example:

@Root(name = "Team")
public class Team {

    @ElementList(name = "Members")
    private List<User> members;
}

With Simple XML, lists and nested structures are easily serialized without manual tag writing.

Best Practices for POJO to XML Conversion

From extensive Android engineering experience:

  • Use Simple XML for annotation-driven object mapping
  • Use XmlSerializer for lightweight or custom XML formats
  • Avoid JAXB in Android unless necessary due to size footprint
  • Always close writers/streams to avoid resource leaks
  • Handle exceptions and invalid characters cleanly
  • Test your XML output for schema or service expectations

These practices lead to stable and maintainable serialization code.

Error Handling and Validation

When serializing:

  • Wrap serialization calls with try/catch
  • Validate your POJO fields (nulls, encodings)
  • Use XML schemas if interacting with external services

Example:

try {
    serializer.write(user, writer);
} catch (Exception ex) {
    Log.e("XML", "Serialization failed", ex);
}

This prevents runtime crashes due to malformed data.

Summary

Converting a POJO to XML in Android is straightforward with the right tools:

  • Simple XML Framework is ideal for annotation-driven, object-oriented serialization
  • XmlSerializer is built into Android and suited for manual control
  • Avoid heavyweight XML binding libraries not suited for mobile

Using these approaches ensures your application can produce XML for services, persistence, and interoperability in a clean and maintainable way.

Visited 5 times, 1 visit(s) today
Close