Java tutorial
import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; public class Main { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Field.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Field field = new Field(); field.name = "myField"; marshaller.marshal(field, System.out); field.status = "citizen"; field.country = "England"; marshaller.marshal(field, System.out); field.status = null; marshaller.marshal(field, System.out); } @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public static class Field { @XmlAttribute String name; @XmlAttribute String status; @XmlAttribute String country; private void beforeMarshal(Marshaller marshaller) { if (country != null && status == null) { throw new RuntimeException("country was set but status was not"); } } } }