views:

125

answers:

2

How to validate a XML in Java, given a XSD Schema?

+3  A: 

Try the following:

File schemaFile = new File("schema.xsd");
File xmlFile = new File("input.xml");
Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new FileInputStream(xmlFile)));
Kevin
A: 

There are a number of examples on how to do this via a quick search. Here is one from Java Ranch that uses JaxP:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);

factory.setAttribute(
      "http://java.sun.com/xml/jaxp/properties/schemaLanguage", 
      "http://www.w3.org/2001/XMLSchema");
factory.setAttribute(
  "http://java.sun.com/xml/jaxp/properties/schemaSource",
  "http://domain.com/mynamespace/mySchema.xsd");
Document doc = null;
try{        
     DocumentBuilder parser = factory.newDocumentBuilder();
     doc = parser.parse("data.xml");
   }
catch (ParserConfigurationException e){
     System.out.println("Parser not configured: " + e.getMessage());
   }
catch (SAXException e){
     System.out.print("Parsing XML failed due to a " + e.getClass().getName() + ":");
     System.out.println(e.getMessage());
   }
catch (IOException e){
     e.printStackTrace();
   }
Ryan Elkins