I am working on serializing some data to an XML file based on third party specifications. The specs appear to be generated by XMLSpy. I understand that optional elements are specified by minOcc=0. I also understand that missing optional data can be represented in an XML doc by either empty elements or by being absent from the XML doc. That said, some third party systems prefer that missing optional data be treated in specific way. ie Some prefer the element to be absent, others prefer that the element be present, but empty. Is there a way to tell from the schema alone, or perhaps an xsd file how missing optional elements should be treated?
-
Am I missing something but shouldn't there be a fundamental difference between a optional element (minOcc=0) and a nullable element ("empty")? – Filburt Nov 21 '13 at 20:46
1 Answers
Is there a way to tell from the schema alone, or perhaps an xsd file how missing optional elements should be treated?
No, not in general, because the semantics of any element, present or absent, are defined by the applications that use the XML, not the schemas that define its validity.
As you mentioned, an XSD can require an element to be present (minOccurs="1"
) or allow it to be absent (minOccurs="0"
). If required to be present, it might be allowed to be empty (nillable="true"
) or not (nillable="false"
). These validity constraints are under your control via XSD but are not ways of treating optional elements, per se.
You mention serialization. There, questions arise as to how to represent null values in data serialized to XML. For example, see Blaise Doughan's answer to How to represent null value as empty element with JAXB? If you're using other applications to perform serialization, search for similar answers specific to those applications. However, at the XSD level, it's only the validity constraints of the sort mentioned above that are under your control. There are more degrees of freedom remaining, and if those matter to you, look to the configuration of the applications using the XML to further refine.