Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 876|回复: 0

XmlBeans的验证方式

[复制链接]

该用户从未签到

发表于 2011-9-14 16:36:37 | 显示全部楼层 |阅读模式
这里介绍两种验证机制:
[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() + "
");
        }
    }
    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)
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

GMT+8, 2024-5-7 02:59 , Processed in 0.393976 second(s), 46 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表