Java / XML
How do I validate an XML file against XSD file?
The Java runtime library supports validation which is backed by Apache Xerces parser.
import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.xml.sax.SAXException; public class XMLValidation { public static void main(String[] args) throws MalformedURLException { URL schemaFile = new URL("http://host:port/filename.xsd"); Source xmlFile = new StreamSource(new File("web.xml")); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); validator.validate(xmlFile); System.out.println(xmlFile.getSystemId() + " is valid."); } catch (SAXException e) { System.out.println(xmlFile.getSystemId() + " is NOT valid xml, The reason is:" + e); } catch (IOException e) { } } }
More Related questions...