1. 程式人生 > >JAXB: 通過schema驗證XML檔案

JAXB: 通過schema驗證XML檔案

在使用JAXB解析XML檔案的時候我們有時候可能會需要通過schema檔案驗證XML的格式,接上文的XMLParser.java

示例程式碼如下:

Java程式碼  收藏程式碼
  1. public static  Object unmarshal(InputStream xml, Class<?> clazz)  throws  SAXException {  
  2.         Object obj = null ;  
  3.         ValidationEventCollector vec = new  ValidationEventCollector();  
  4.         try
     {  
  5.             SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);  
  6.             Schema schema = sf.newSchema(new  File( "C://eclipse//workspace1//STAF//test//employees.xsd" ));  
  7.             JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName());  
  8.             Unmarshaller u = jc.createUnmarshaller();  
  9.             u.setSchema(schema);  
  10.             u.setEventHandler(vec);  
  11.             obj = u.unmarshal(xml);  
  12.         } catch  (JAXBException e) {  
  13.             throw new  RuntimeException( "Can't unmarshal the XML file, error message: "  + e.getMessage());  
  14.         } finally  {  
  15.             if
    (vec !=  null  && vec.hasEvents()) {  
  16.                 for (ValidationEvent ve : vec.getEvents()) {  
  17.                     String msg = ve.getMessage();  
  18.                     ValidationEventLocator vel = ve.getLocator();  
  19.                     int  line = vel.getLineNumber();  
  20.                     int  column = vel.getColumnNumber();  
  21.                     System.out.println();  
  22.                     System.err.println("At line "  + line +  ", column "  + column +  ": "  + msg);  
  23.                 }  
  24.             }  
  25.         }  
  26.         return  obj;  
  27.     }  
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;
	}