引用
jaxb是一个读写xml的工具,还可以提供验证,不需要额外的jar
1. XSD sample
<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.example.org/draft_2/" targetNamespace="http://www.example.org/draft_2/"> <xs:complexType name="BaseCommonRefCType"> <xs:sequence> <xs:element name="name"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:minLength value="1" /> <xs:maxLength value="64" /> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="type" maxOccurs="1" minOccurs="0"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:minLength value="1" /> <xs:maxLength value="64" /> <xs:enumeration value="filter" /> <xs:enumeration value="nzload" /> <xs:enumeration value="db_system" /> <xs:enumeration value="repetition_group" /> <xs:enumeration value="system_path" /> <xs:enumeration value="record" /> <xs:enumeration value="report" /> <xs:enumeration value="mapping" /> <xs:enumeration value="table" /> <xs:enumeration value="cob" /> <xs:enumeration value="file_container" /> <xs:enumeration value="node" /> <xs:enumeration value="instance" /> <xs:enumeration value="stage" /> <xs:enumeration value="java_config" /> <xs:enumeration value="business_date" /> <xs:enumeration value="matrix" /> <xs:enumeration value="database" /> <xs:enumeration value="file_pattern" /> <xs:enumeration value="gemfire_region" /> <xs:enumeration value="task" /> <xs:enumeration value="config_file" /> <xs:enumeration value="dataflow" /> <xs:enumeration value="ems" /> <xs:enumeration value="workflow" /> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> </xs:complexType> </xs:schema>
2. 根据xsd生成java类
xjc -p com.wilson test.xsd -d src
3. Sample class for retrieving classes from xml
public class JAXBUtil { private static final Log logger = LogFactory.getLog(JAXBUtil.class.getName()); public static YourClass retrieveObjectFromXML(File xml, URL xsdURL) { ProcessLifeCycle lifeCycle = null; JAXBContext jaxbContext; ValidationEventCollector vec = new ValidationEventCollector(); try { jaxbContext = JAXBContext.newInstance(YourClass.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(xsdURL)); unmarshaller.setEventHandler(vec); lifeCycle = (ProcessLifeCycle) unmarshaller.unmarshal(xml); } catch (JAXBException e) { logger.error("", e); } catch (SAXException e) { logger.error("", e); } 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(); throw new RuntimeException("Can't unmarshal the XML file, error message: " + " At line " + line + ", column " + column + ": " + msg); } } } return lifeCycle; } }