如何用java验证XML schema

以前验证XML一直使用dtd的,今天尝试着用xsd作验证,可是网上的例子一直跑不起来。折腾了半天才发现是例子里面对于XML文件的命名空间没有设置清楚,这里解决下方案记录:

 

[note.xml]

 



 Tove
 Jani
 Reminder
 Don't forget me this weekend!

 

  网上的例子就是在这里没设置对xmlns,这里的xmlns一定要和下面note.xsd中的targetNamespace和xmlns一致

 

[note.xsd]

 



	
		
			
				
				
				
				
			
		
	

 

[java]

 

  

  String configFileLocation = "/note.xml";
        String xsdFileLocation = "/note.xsd";
        InputStream configInputStream = this.getClass().getResourceAsStream(configFileLocation);
        if (configInputStream == null) {
            throw new IllegalArgumentException("can not find resource[" + configFileLocation + "]");
        }

        InputStream xsdInputStream = this.getClass().getResourceAsStream(xsdFileLocation);
        if (xsdInputStream == null) {
            throw new IllegalArgumentException("can not find resource[" + xsdFileLocation + "]");
        }

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new SAXSource(new InputSource(xsdInputStream)));
        factory.setSchema(schema);

        DocumentBuilder builder = factory.newDocumentBuilder();

        builder.setErrorHandler(new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw new RuntimeException(exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                throw new RuntimeException(exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw new RuntimeException(exception);
            }
        });

        document = builder.parse(configInputStream);

        System.out.println(document);

 

你可能感兴趣的:(java)