How do I prevent bean’s property being serialized to XML?

package org.kodejava.bean;

import java.beans.*;

public class BeanToXmlTransient {
    private Long id;
    private String itemName;
    private String itemColour;
    private Integer itemQuantities;

    static {
        try {
            // In this block will change the attribute type of the 
            // itemQuantities to transient, so it will be not serialized 
            // to xml when we use XMLEncode to convert the bean to xml 
            // persistence.
            BeanInfo bi = Introspector.getBeanInfo(BeanToXmlTransient.class);
            PropertyDescriptor[] pds = bi.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : pds) {
                if (propertyDescriptor.getName().equals("itemQuantities")) {
                    propertyDescriptor.setValue("transient", Boolean.TRUE);
        } catch (IntrospectionException e) {

    public static void main(String[] args) {
        BeanToXmlTransient bean = new BeanToXmlTransient();
        bean.setItemColour("Dark Red");

        try {
            XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
                    new FileOutputStream("BeanTransient.xml")));

            // Write an XML representation of the specified object to the 
            // output.
        } catch (FileNotFoundException e) {

    public Long getId() {
        return id;

    public void setId(Long id) { = id;

    public String getItemName() {
        return itemName;

    public void setItemName(String itemName) {
        this.itemName = itemName;

    public String getItemColour() {
        return itemColour;

    public void setItemColour(String itemColour) {
        this.itemColour = itemColour;

    public Integer getItemQuantities() {
        return itemQuantities;

    public void setItemQuantities(Integer itemQuantities) {
        this.itemQuantities = itemQuantities;

Here will see the the itemQuantities property is not serialized to XML.

<?xml version="1.0" encoding="UTF-8"?>
<java version="17" class="java.beans.XMLDecoder">
 <object class="org.kodejava.bean.BeanToXmlTransient">
  <void property="id">
  <void property="itemColour">
   <string>Dark Red</string>
  <void property="itemName">

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.