Create your own xml validator

Given the task to write your own validator xml file for xsd in java.
I found a lot of different online validators on the Internet, but I don't understand how they work. How exactly is the well-formed and valid xml file checked?

Author: enzo, 2016-03-08

1 answers

The fact is that the javax.xml package for working with XML in Java includes only abstractions (this is an API), and the implementation of depends on the version of the JDK. You can see the implementation of the standard xerces validator here, but it is far from simple and will hardly help with your task.

Task verbatim-Write a simple validator to check the xml document for syntactic correctness and compliance of primitive types with xsd

If you understand this the task is also verbatim as it is written, then you can do this:

  • Preparing an XSD document. Include only primitive types in it, since only they appear in the task;
  • Write an XSD reader that runs through the XSD parser and just makes a dictionary of elements in the form of LinkedHashMap, where key is the name of the element / tag, value - tag type;
  • Write a simple helper with a set of static methods that check for compliance like: isInteger(), isDouble() etc. You can only limit yourself to the basic ones;
  • Write the validator itself, pass it the schema and the document. Run through the document with the parser and check with the dictionary that you have compiled above. On its basis, you can throw exceptions if: the tag is missing in the scheme, the tag goes in the wrong sequence, the element type does not match.

If desired, all this can be built on the basis of JAXP, with Errorhadler etc.

If you need complex types, nesting, or more complex conditions, then you will need to build more complex constraints. In such cases, it is generally good to ask the interviewer what specific knowledge he wants you to demonstrate by inventing such synthetic tasks.

 1
Author: enzo, 2016-03-10 05:24:02