XML validation using Apache Xerces - Java

Viewed 22

I'm trying to validate XML using external XSD in java. But the examples I have seen are adding dependency of Xerces but importing SchemaFactory , etc from javax.xml

Why this is so ? How to validate Xml using Xerces in java ?

1 Answers

You really don't need an external dependency to Xerces. The JVM contains its own Xerces version. But the internal version's package structure differs from external Xerces.

Internal package is: com.sun.org.apachge.xerces.

External package is: org.apache.xerces.

java.xml is only an abstraction layer to the implementing classes provided e.g. by Xerces.

The default implementation is the internal Xerces version. But if you include the external Xerces Jars, there is a mechanism to use the external implementation automatically.

E.g. look inside xercesImpl.jar (I downloaded the binary distribution of Xerces 2.12.2). Under META-INF/services there are some text files like javax.xml.validation.SchemaFactory.

The content of javax.xml.validation.SchemaFactory is:

org.apache.xerces.jaxp.validation.XMLSchemaFactory

So at runtime, if xercesImpl.jar is on the classpath you get this class as the implementation for SchemaFactory.

The underlying mechanism is documented in class java.util.ServiceLoader.

Related