2010-02-19 69 views

回答

3

尝试以下操作:

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))); 
0

有许多关于如何通过快速搜索做这方面的例子。以下是使用JaxP的Java Ranch之一:

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(); 
    }