JAXB: 通過schema驗證XML檔案
阿新 • • 發佈:2019-01-29
在使用JAXB解析XML檔案的時候我們有時候可能會需要通過schema檔案驗證XML的格式,接上文的XMLParser.java
示例程式碼如下:
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
- 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;
- }
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;
}