0

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?

Community
  • 1
  • 1
riha
  • 2,270
  • 1
  • 23
  • 40
  • If it's optional and it's not present then why would you need to add the node? – ChadNC Mar 27 '12 at 14:43
  • see http://stackoverflow.com/questions/9884051/how-to-update-xml-file-from-another-xml-file-dynamically/9884503#9884503 – Riddhish.Chaudhari Mar 28 '12 at 06:11
  • It's supposed to be a config.xml and whenever elements are missing in xml, the augmented `Document` should just use the defaults from the xsd so the code doesn't have to bother with defaults. – riha Mar 29 '12 at 08:15

1 Answers1

0

This answer quotes the spec: augmentation applies default values to empty elements. It does NOT add elements that are not present in xml.

In other words, augmentation by schema cannot guarantee that elements are present.

Community
  • 1
  • 1
riha
  • 2,270
  • 1
  • 23
  • 40