XmlBeans的验证方式
版权声明:原创作品,如需转载,请与作者联系。否则将追究法律责任。 |
这里介绍两种验证机制: [1]更新文档(xml)后,收集验证错误信息; [2]更新文档(xml)时,直接抛出错误验证异常. 实例中使用的xml和xsd(注:此实例为xmlbeans下载包中samples中代码,笔者做了简单修改,使之在自定义环境下运行,该代码遵循Apache License V2.) todolist.xml <?xml version="1.0" encoding="UTF-8"?> <todolist xmlns="http://xmlbeans.apache.org/samples/validation/todolist"> <item id="001"> <name>Buy a south Pacific island.</name> <description>Contingent on inheriting lots of money.</description> <due_by>2005-05-01T23:36:28</due_by> <action>someday_maybe_defer</action> </item> <item id="002"> <name>Get that new PowerBook I've been eyeing.</name> <description>Resulting productivity increase will be exponential!</description> <due_by>2005-05-01T23:36:28</due_by> <action>do</action> </item> <item id="003"> <name>Clean the garage.</name> <description>Remove at least enough junk so that my bicycle fits.</description> <due_by>2005-05-30T23:36:28</due_by> <action>delegate</action> </item> </todolist> todolist.xsd <?xml version="1.0" encoding="UTF-8"?> <xs:schema targetNamespace="http://xmlbeans.apache.org/samples/validation/todolist" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlbeans.apache.org/samples/validation/todolist" elementFormDefault="qualified"> <xs:element name="todolist"> <xs:complexType> <xs:sequence> <xs:element name="item" type="itemType" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="itemType"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="description" type="xs:string" minOccurs="0"/> <xs:element name="due_by" type="xs:dateTime" minOccurs="0"/> <xs:element name="action" type="actionType"/> </xs:sequence> <xs:attribute name="id" type="idType"/> </xs:complexType> <xs:simpleType name="nameType"> <xs:restriction base="xs:string"> <xs:maxLength value="50"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="idType"> <xs:restriction base="xs:int"> <xs:maxExclusive value="100"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="actionType"> <xs:restriction base="xs:string"> <xs:enumeration value="do"/> <xs:enumeration value="delegate"/> <xs:enumeration value="someday_maybe_defer"/> <xs:enumeration value="toss"/> <xs:enumeration value="incubate"/> <xs:enumeration value="file"/> </xs:restriction> </xs:simpleType> </xs:schema> 使用的用于验证的Java类如下所示. 其中isValidAfterChanges()方法在更新xml时,如果发现更新的数据不符合相应的xsd,则会将验证失败的信息保存在一个ArrayList中,可以自由选择输出这些信息或忽略; isValidOnTheFly()方法在更新xml时,如果发现更新的数据不符合相应的xsd,则会立即抛出验证错误异常. Validation.java package net.zj.xmlbeans.validation; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; import org.apache.xmlbeans.samples.validation.todolist.ItemType; import org.apache.xmlbeans.samples.validation.todolist.TodolistDocument; import org.apache.xmlbeans.samples.validation.todolist.TodolistDocument.Todolist; public class Validation { private static XmlOptions m_validationOptions; public boolean isValidAfterChanges(String xmlPath) { System.out.println("Validating after changes:"); // Set up the validation error listener. ArrayList<String> validationErrors = new ArrayList<String>(); m_validationOptions = new XmlOptions(); m_validationOptions.setErrorListener(validationErrors); TodolistDocument todoList = (TodolistDocument) parseXml(xmlPath, null); // Schema defines the <name> element as required (minOccurs = '1'). // Add an error. todoList.getTodolist().getItemArray(0).setName(null); // During validation, errors are added to the ArrayList for // retrieval and printing by the printErrors method. boolean isValid = todoList.validate(m_validationOptions); if (!isValid) { printErrors(validationErrors); } return isValid; } public boolean isValidOnTheFly(String xmlPath) { System.out.println("Validating on-the-fly:"); m_validationOptions = new XmlOptions(); m_validationOptions.setValidateOnSet(); TodolistDocument todoList = (TodolistDocument) parseXml(xmlPath, m_validationOptions); Todolist list = todoList.getTodolist(); ItemType firstItem = list.getItemArray(0); // Schema defines the <id> element as allowing values up to 100. // Add an error. firstItem.setId(8587); // This line will not be reached. return todoList.validate(); } public void printErrors(ArrayList<String> validationErrors) { System.out.println("Errors discovered during validation:"); Iterator<String> iter = validationErrors.iterator(); while (iter.hasNext()) { System.out.println(">> " + iter.next() + "\n"); } } public XmlObject parseXml(String xmlFilePath, XmlOptions validationOptions) { File xmlFile = new File(xmlFilePath); XmlObject xml = null; try { xml = XmlObject.Factory.parse(xmlFile, validationOptions); } catch (XmlException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return xml; } public static void main(String[] args) { Validation thisSample = new Validation(); String xmlPath = "docs/todolist.xml"; // Use the validate method to validate an instance after // updates. thisSample.isValidAfterChanges(xmlPath); // Use the VALIDATE_ON_SET option to validate an instance // as updates are made. thisSample.isValidOnTheFly(xmlPath); } } 结果: Validating after changes: Errors discovered during validation: >> /root/dev_home/workspace/[ct]XmlBeans/docs/todolist.xml:0: error: cvc-elt.3.1: Element has xsi:nil attribute but is not nillable in element item@http://xmlbeans.apache.org/samples/validation/todolist Validating on-the-fly: Exception in thread "main" org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException: int value (8,587) is greater than or equal to maxExclusive facet (100) for idType in namespace http://xmlbeans.apache.org/samples/validation/todolist at org.apache.xmlbeans.impl.values.XmlObjectBase$ValueOutOfRangeValidationContext.invalid(XmlObjectBase.java:285) at org.apache.xmlbeans.impl.values.JavaIntHolderEx.validateValue(JavaIntHolderEx.java:140) at org.apache.xmlbeans.impl.values.JavaIntHolderEx.set_int(JavaIntHolderEx.java:55) at org.apache.xmlbeans.impl.values.XmlObjectBase.set(XmlObjectBase.java:1609) at org.apache.xmlbeans.impl.values.XmlObjectBase.setIntValue(XmlObjectBase.java:1541) at org.apache.xmlbeans.samples.validation.todolist.impl.ItemTypeImpl.setId(Unknown Source) at net.zj.xmlbeans.validation.Validation.isValidOnTheFly(Validation.java:85) at net.zj.xmlbeans.validation.ValidationTest.main(ValidationTest.java:36) 本文出自 “子 孑” 博客,转载请与作者联系! 本文出自 51CTO.COM技术博客 |



todolist.xml
zhangjunhd
博客统计信息
热门文章
最新评论
友情链接


