5 minutes

How to Convert POJO to XML in Android

By Nilanchala @nilan, On Sep 17, 2023 Android 2.22K Views

POJO is an acronym for Plain Old Java Object, basically a class with attributes and it’s getters and setters. The name is used to emphasize that a given object is an ordinary Java Object, not a special object. The term “POJO” is mainly used to denote a Java object which does not follow any of the major Java object models, conventions, or frameworks.

Below example reads the pojo object instance variable and generates xml tags and values in the order of variable declaration in the given pojo class. You can assign tag names for each element.

public class Student {
	String name;
	String section;
	String id;

	public Student(String name, String id, String section) { = name; = id;
		this.section = section;

	public String getName() {
		return name;

	public void setName(String name) { = name;

	public String getSection() {
		return section;

	public void setSection(String section) {
		this.section = section;

	public String getId() {
		return id;

	public void setId(String id) { = id;


import org.xmlpull.v1.XmlSerializer;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.widget.TextView;

public class MainActivity extends Activity {
	TextView textView;

	protected void onCreate(Bundle savedInstanceState) {
		textView = (TextView) findViewById(;

		Student pojo = new Student("Adam" , "100120", "Grade 6");
		// Serialization begins:
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		try {
			// start document
			serializer.startDocument("UTF-8", true);
			serializer.setFeature("", true);

			serializer.startTag("", "students");
			serializer.startTag("", "student");
			serializer.attribute("", "ID", pojo.getId());
			serializer.startTag("", "name");
			serializer.endTag("", "name");
			serializer.startTag("", "section");
			serializer.endTag("", "section");
			serializer.endTag("", "student");
			serializer.endTag("", "students");

			// end document.

			Log.i("Pojo to xml", writer.toString());
			textView.setText("" + writer.toString());
			// Toast.makeText(getApplicationContext(), ""+ writer.toString(), 0).show();
		} catch (IllegalArgumentException e) {
		} catch (IllegalStateException e) {
		} catch (IOException e) {


Output XML

<student ID="100120">
<section>Grade 6</section>

nilan avtar


I'm a blogger, educator and a full stack developer. Mainly focused on Java, Spring and Micro-service architecture. I love to learn, code, make and break things.