package com.songjy.xml; import java.io.File; import java.io.IOException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.dom4j.Document; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.SAXValidator; import org.dom4j.io.XMLWriter; import org.dom4j.util.XMLErrorHandler; import org.xml.sax.SAXException; public class ValidateXML { public boolean validate_xml(String xsd_file_path,String xml_file_path) throws SAXException,IOException { // 建立schema工厂 SchemaFactory schemaFactory = SchemaFactory .newInstance("http://www.w3.org/2001/XMLSchema"); // 建立验证文档文件对象,利用此文件对象所封装的文件进行schema验证 File schemaFile = new File(xsd_file_path); // 利用schema工厂,接收验证文档文件对象生成Schema对象 Schema schema = schemaFactory.newSchema(schemaFile); // 通过Schema产生针对于此Schema的验证器,利用schenaFile进行验证 Validator validator = schema.newValidator(); // 得到验证的数据源 Source source = new StreamSource(xml_file_path); // 开始验证,成功输出success!!!,失败输出fail try { validator.validate(source); return true; } catch (Exception ex) { ex.printStackTrace(); return false; } } public void xml_validate(String xsd_file_path,String xml_file_path) { try { // 创建默认的XML错误处理器 XMLErrorHandler errorHandler = new XMLErrorHandler(); // 获取基于 SAX 的解析器的实例 SAXParserFactory factory = SAXParserFactory.newInstance(); // 解析器在解析时验证 XML 内容。 factory.setValidating(true); // 指定由此代码生成的解析器将提供对 XML 名称空间的支持。 factory.setNamespaceAware(true); // 使用当前配置的工厂参数创建 SAXParser 的一个新实例。 SAXParser parser = factory.newSAXParser(); // 创建一个读取工具 SAXReader xmlReader = new SAXReader(); // 获取要校验xml文档实例 Document xmlDocument = (Document) xmlReader.read(new File( xml_file_path)); // 设置 XMLReader 的基础实现中的特定属性。核心功能和属性列表可以在 // [url]http://sax.sourceforge.net/?selected=get-set[/url] 中找到。 parser.setProperty( "http://java.sun.com/xml/jaxp/properties/schemaLanguage","http://www.w3.org/2001/XMLSchema"); parser.setProperty( "http://java.sun.com/xml/jaxp/properties/schemaSource","file:" + xsd_file_path); // 创建一个SAXValidator校验工具,并设置校验工具的属性 SAXValidator validator = new SAXValidator(parser.getXMLReader()); // 设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。 validator.setErrorHandler(errorHandler); // 校验 validator.validate(xmlDocument); XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); // 如果错误信息不为空,说明校验失败,打印错误信息 if (errorHandler.getErrors().hasContent()) { System.out.println("XML文件通过XSD文件校验失败!"); writer.write(errorHandler.getErrors()); } else { System.out.println("Good! XML文件通过XSD文件校验成功!"); } } catch (Exception ex) { System.out.println("XML文件: " + xml_file_path + " 通过XSD文件:" + xsd_file_path + "检验失败。\n原因: " + ex.getMessage()); ex.printStackTrace(); } } }
XSD示例文件
<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="Test"> <xs:complexType> <xs:choice maxOccurs="unbounded" minOccurs="0"> <xs:element name="NewData"> <xs:complexType> <xs:complexContent> <xs:extension base="dataElementType"> <xs:attributeGroup ref="datarequiredAttributeType" /> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="ModifyData"> <xs:complexType> <xs:complexContent> <xs:extension base="dataElementType"> <xs:attributeGroup ref="datarequiredAttributeType" /> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="DeleteData"> <xs:complexType> <xs:complexContent> <xs:extension base="dataElementType"> <xs:attributeGroup ref="datarequiredAttributeType" /> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> </xs:choice> <xs:attribute name="id" type="stringRequireType24" use="required" /> </xs:complexType> </xs:element> <xs:attributeGroup name="datarequiredAttributeType"> </xs:attributeGroup> <xs:complexType name="dataElementType"> <xs:all> <xs:element name="deviceTypeId" type="stringType10" minOccurs="0" /> <xs:element name="iconName" type="stringType100" minOccurs="0" /> </xs:all> </xs:complexType> <xs:simpleType name="stringType10"> <xs:restriction base="xs:string"> <xs:pattern value="([0-9])*" /> <xs:minLength value="0" /> <xs:maxLength value="10" /> </xs:restriction> </xs:simpleType> <xs:simpleType name="stringType100"> <xs:restriction base="xs:string"> <xs:minLength value="0" /> <xs:maxLength value="100" /> </xs:restriction> </xs:simpleType> <xs:simpleType name="stringRequireType24"> <xs:restriction base="xs:string"> <xs:minLength value="1" /> <xs:maxLength value="24" /> </xs:restriction> </xs:simpleType> <xs:simpleType name="stringRequireType50"> <xs:restriction base="xs:string"> <xs:minLength value="1" /> <xs:maxLength value="50" /> </xs:restriction> </xs:simpleType> </xs:schema>
xml示例文件
<?xml version="1.0" encoding="UTF-8"?> <Test id="F2009045002100N03030100"> <NewData> <deviceTypeId>16135</deviceTypeId> <iconName>变电站.gif</iconName> </NewData> </Test>
Xsd文件验证xml的java实现
Java通过XML Schema校验XML
使用反射递归校验XML对象空(null)字段
package com.wasu.util; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import javax.xml.bind.annotation.XmlElement; import org.apache.commons.lang3.StringUtils; public class XmlValidate { public static final String ISNULL = "节点为空(或不存在)"; public static Map<String,String> validate(Object obj) throws IllegalAccessException,InvocationTargetException,NoSuchMethodException { Map<String,String> map = new HashMap<String,String>(); if (null != obj) { Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { if (false == field.isAnnotationPresent(XmlElement.class)) continue;// 假如没有注解XmlElement则跳过 XmlElement e = field.getAnnotation(XmlElement.class); if (false == e.required()) continue;// 假如不是必须节点则跳过 String name = StringUtils.isBlank(e.name()) ? field.getName() : e.name(); Object v = getProperty(obj,field.getName()); Class<?> t = field.getType(); if (null == v) { map.put(name,ISNULL); continue; } if (t == String.class && StringUtils.isBlank(v.toString())) { map.put(name,ISNULL); continue; } if (t.getPackage().getName().startsWith("java")) continue; map.putAll(validate(v)); } } return map; } public static Object getProperty(Object obj,String name) throws IllegalAccessException,NoSuchMethodException { if (null != obj && StringUtils.isNotBlank(name)) { Method get = obj.getClass().getMethod("get" + StringUtils.capitalize(name),parameterTypes); return get.invoke(obj,args); } return null; } private static final Class<?>[] parameterTypes = {}; private static final Object[] args = {}; }原文链接:https://www.f2er.com/xml/299341.html