Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
validate xml against xsd in java
import java.io.InputStream;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
public class CmsSchemaResourceResolver implements LSResourceResolver {
private DOMImplementationLS domImplementationLS;
private final String relativePath;
public CmsSchemaResourceResolver(final String relativePath) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
this.relativePath = relativePath;
System.setProperty(DOMImplementationRegistry.PROPERTY, "org.apache.xerces.dom.DOMImplementationSourceImpl");
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
domImplementationLS = (DOMImplementationLS) registry.getDOMImplementation("LS");
}
//-------------------------------------------------------------------------------------------------
// Resolve the schmea file relative to the given location from the classpath
//-------------------------------------------------------------------------------------------------
public LSInput resolveResource(String type, String namespaceURI,
String publicId, String systemId, String baseURI) {
LSInput input = domImplementationLS.createLSInput();
InputStream inputStream = CmsSchemaResourceResolver.class.getResourceAsStream(relativePath + systemId);
input.setByteStream( inputStream );
input.setSystemId( systemId );
return input;
}
}
private static boolean validate(InputStream xsdInputStream, InputStream xmlInputStream) throws Exception{
SchemaFactory schemaFactory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI );
schemaFactory.setResourceResolver( new CmsSchemaResourceResolver( "/" ) );
Source schemaSource = new StreamSource(xsdInputStream);
Schema schema = schemaFactory.newSchema( schemaSource );
Source contentFile = new StreamSource(xmlInputStream);
Validator validator = schema.newValidator();
try {
validator.validate( contentFile );
log.debug("Generated xml is valid.");
return true;
} catch(Throwable exc) {
log.debug("Generated xml is not valid.");
exc.printStackTrace();
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment