Java HTML / XML How to - Make an optional attribute required if another optional attribute is set








Question

We would like to know how to make an optional attribute required if another optional attribute is set.

Answer

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;
// w  w w. j  ava  2  s  . c  o m
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");
      }
    }

  }

}