JAXB: 通过schema验证XML文件

接上文 JAXB:使用annotation绑定XML(xmlns)

 

在使用JAXB解析XML文件的时候我们有时候可能会需要通过schema文件验证XML的格式,接上文的XMLParser.java

 

示例代码如下:

public static Object unmarshal(InputStream xml, Class<?> clazz) throws SAXException {
		Object obj = null;
		
		ValidationEventCollector vec = new ValidationEventCollector();
		
		try {
			SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File("C:\\eclipse\\workspace1\\STAF\\test\\employees.xsd"));
			
			JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName());
			Unmarshaller u = jc.createUnmarshaller();
			u.setSchema(schema);
            u.setEventHandler(vec);
			
			obj = u.unmarshal(xml);
		} catch (JAXBException e) {
			throw new RuntimeException("Can't unmarshal the XML file, error message: " + e.getMessage());
		} finally {
			if(vec != null && vec.hasEvents()) {
            	for(ValidationEvent ve : vec.getEvents()) {
            		String msg = ve.getMessage();
            		ValidationEventLocator vel = ve.getLocator();
            		int line = vel.getLineNumber();
            		int column = vel.getColumnNumber();
            		System.out.println();
            		System.err.println("At line " + line + ", column " + column + ": " + msg);
            	}
            }
		}
		
		return obj;
	}

 

该代码段适用于单一schema,或者在classpath中的多schema验证,如果是classpath外的多schema验证,请结合参考该文:XML validation for multiple schemas 验证使用多个XSD schema的XML文件

你可能感兴趣的:(eclipse,C++,c,xml,C#)