javax.xml.validation.Validator has a method to validate and augment xml against a schema.
Simplified xml:
<something>
<sub1>false</sub1> <!-- Suppose sub1 is optional and may not be present in xml -->
<sub2>false</sub2>
</something>
Simplified xsd:
<complexType name="something">
<sequence>
<element name="sub1" type="boolean" maxOccurs="1" minOccurs="0" default="false"/>
<element name="sub2" type="boolean" maxOccurs="1" minOccurs="1"/>
</sequence>
</complexType>
Simplified validation and augmentation code:
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File(xmlFile));
DOMSource input = new DOMSource(document);
DOMResult output = new DOMResult();
validator.validate(input, output);
Document result = (Document)output.getNode();
So, besides validating xml against the schema, it should also augment it and add any missing defaults (like sub1) and send that into output
.
However, sub1
is not present in result
when it is missing in xml.
Where am I off track here?
EDIT:
Ok, found the reason why sub1
is missing. But how can I ensure that sub1
is present in result
even when it's not in xml?