Preventing a property from being marshalled to xml file

By default all properties of an instance are marshalled as elements in an xml file. As shown below..

Marshalling an Country insance with below class structure

Country

package package2;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Country {
    private int id;
    private String name;
    private int population;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getPopulation() {
        return population;
    }
    public void setPopulation(int population) {
        this.population = population;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("name:").append(this.name).append(",");
        sb.append("population:").append(this.population).append("}");

        return sb.toString();
    }
}

will result in below xml
<?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>
<country>
<id>1</id>
<name>India</name>
<population>10000000</population>
</country>

If we don’t want population attribute from being marshalled, we can achieve that by marking the “getPopulation” getter with annotation @XmlTransient as shown below

@XmlTransient
public int getPopulation() {
    return population;
}

will result in below xml
<?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>
<country>
<id>1</id>
<name>India</name>
</country>

Main Code

package package2;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

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

public class XMLTransientDemo {
    public static void main(String[] args) throws JAXBException, IOException {
        JAXBContext jaxbContext = JAXBContext.newInstance(Country.class);

        Marshaller marshaller = jaxbContext.createMarshaller();
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        File file = new File("result.xml");
        FileWriter fw = new FileWriter(file);

        Country country = new Country();
        country.setId(1);
        country.setName("India");
        country.setPopulation(10000000);
        
        marshaller.marshal(country, fw);
    }
}

Leave a Reply