`
liugang594
  • 浏览: 987618 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Java中使用Schema验证

阅读更多

by Neeraj Bajaj

The Java API for XML Processing (JAXP) 1.3 was initially introduced in Java 2 Platform, Standard Edition (J2SE) 5.0 and is also now available in the Java Web Services Developer Pack (Java WSDP). JAXP 1.3 adds a new Schema Validation Framework (SVF), also called the Validation API, which offers advanced capabilities to efficiently validate XML against a schema. SVF also provides for much faster performance as compared to the schema validation approach in JAXP 1.2.

Before examining SVF, let's look at the earlier schema validation approach. Here's a code snippet that demonstrates that approach for SAX parsing:

   SAXParserFactory sf = SAXParserFactory.newInstance();
   sf.setNamespaceAware(true); 
   sf.setValidating(true);            
   SAXParser sp = sf.newSAXParser();
   sp.setProperty(
     SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
   sp.setProperty(SCHEMA_SOURCE, schema);
   sp.parse(new File(xml), dh);

The basic steps are:

  1. Create a SAXParserFactory object.
  2. Configure the SAXParserFactory object to produce parsers that support XML namespaces, and that validate documents as they are parsed.
  3. Create a SAX parser.
  4. Set SAX parser properties for the schema language and the schema source. In this example, the schema is the W3C XML Schema.
  5. Parse the document.

 

Notice that this process couples validation and XML processing.

By comparison, in the SVF approach, XML document validation against a schema is decoupled from XML processing. The first step in the SVP approach is to compile the schema:

   final String sl = XMLConstants.W3C_XML_SCHEMA_NS_URI;
   SchemaFactory factory = SchemaFactory.newInstance(sl);
   StreamSource ss = new StreamSource("mySchema.xsd");
   Schema schema = factory.newSchema(ss);

SchemaFactory is a schema compiler. It reads the given schema, checks the schema syntax and semantics according to the constraints imposed by the specified schema language, and returns a Schema object that is an immutable memory representation of the schema. Immutable here means that the set of constraints are not changed once the Schema object is created. An application that validates the same document twice against the same Schema object, must always produce the same result.

Next, you validate an XML document against the schema. There are three approaches to choose from depending upon your requirements:

  • Set the Schema instance on a DocumentBuilderFactory or SAXParserFactory
  • Create a Validator
  • Create a ValidatorHandler (to validate a SAX stream)

 

All three approaches guarantee that the XML document is validated only against the schema from which the Schema instance was obtained.

Lets look at the first approach, setting the Schema instance on a factory:

   SAXParserFactory spf = SAXParserFactory.newInstance();
   spf.setSchema(schema);
   SAXParser parser = spf.newSAXParser();
   parser.parse(<XML DOCUMENT>);

Here, the same Schema instance is passed to all the SAXParser instances created from this SAXParserFactory. The SAXParser object parses the XML document and simultaneously validates itagainst the Schema instance. Because the SAXParser does not repeatedly load the schema for every XML document that needs to be validated, this approach considerably improves the performance of the overall schema validation process. Compare this to the previous approach, where the specified schema is repeatedly loaded for every XML document that needs to be validated.

After you load a Schema object into memory, you can take the second approach, that is, use a Validator to validate an XML document against that Schema object. First you create a Validator object from the Schema object. Then you call the validate() method in the Validator object to do the validation:

   Validator v = schema.newValidator();
   v.validate(new StreamSource(xml));

The Validator object accepts java.xml.transform.Source as input. This means that it can accept either an event-based, SAX source (SAXSource) or an object-based, Document Object Model (DOM) source (DOMSource). By accepting DOMSource as input, the Validator is capable of validating an in-memory DOM Document or node against the given Schema object.

   Validator v = schema.newValidator();
   v.validate(new DOMSource(<DOM NODE>));

You might consider the Validator approach if your requirement is to validate a DOM node, or you are given a SAXSource. This approach works even if the implementation of the SAX driver is from a different vendor.

The third approach is to create a specially-designed javax.xml.validation.ValidatorHandler to validate SAX events:

   SAXParserFactory spf = SAXParserFactory.newInstance();
   spf.setNamespaceAware(true);
   XMLReader reader = spf.newSAXParser().getXMLReader();
   ValidatorHandler vh =  schema.newValidatorHandler();
   //key is to set "ValidatorHandler" as ContentHandler 
   //so that SAX event can be validated
   reader.setContentHandler(vh);
   reader.parse(xml);  

Notice that to validate the SAX events, you need to set the ValidatorHandler as the ContentHandler.

Using a ValidatorHandler, you can also validate a JDOM document against the schema. In fact, any object model (such as XOM and DOM4J) which can be built on top of a SAX stream or can produce SAX events can be used with the SVF to validate an XML document against a schema. This is possible because the ValidationHandler can validate a SAX stream. Here is a code snippet that illustrates how a JDOM document can be validated against a schema, it assumes that you obtained a ValidatorHandler as shown in the previous example:

   SAXOutputter so = new SAXOutputter(vh);
   so.output(jdomDocument);

The SAXOutputter object fires SAX events for the JDOM document. The SAX events are then validated by the ValidatorHandler.

There are other things you can do using the SVF, such as validate XML after transformation or obtain schema type information. For more information about using the SVF see the article Easy and Efficient XML Processing: Upgrade to JAXP 1.3

分享到:
评论

相关推荐

    java中实现xmlschema验证文件借鉴.pdf

    总的来说,Java中的XML Schema验证是一个关键的过程,它确保了XML数据的准确性和一致性,从而降低了程序处理数据时出错的风险。通过正确地构建和使用XSD,开发者可以构建更加健壮、可靠的XML处理系统。

    java中实现xmlschema验证文件参照.pdf

    在Java中实现XML Schema验证文件,主要是为了确保XML文档遵循预定义的结构和规则,从而保证数据的正确性和一致性。XML Schema(XSD)是一种用于定义XML文档结构和数据类型的规范,它提供了比DTD(Document Type ...

    Java bean转换为Json Schema

    在Java中,将Bean转换为Json Schema可以帮助我们在服务器端验证客户端发送的数据是否符合预设的模式,避免因数据格式错误导致的问题。这种转换通常通过一些库或工具来实现,例如`json-schema-generator`或`org.json...

    Java通过XML Schema校验XML

    因此,本文将重点介绍如何使用DOM4j结合javax.xml.parsers包中的API来实现XML的有效性校验证。 #### DOM4j与XSD校验 在本例中,作者选择使用DOM4j库来进行XML的解析与校验,并且结合了javax.xml.parsers包中的...

    JSON Schema 校验库——json-schema-validator(java版本).rar

    4. **与其他框架的集成**:库可以方便地与Spring、Jackson、Gson等Java JSON处理框架集成,使得在整个应用程序中实现JSON Schema验证变得简单。 5. **性能优化**:虽然JSON Schema验证可能涉及复杂的递归和规则检查...

    Schema校验java

    在Java中实现XML Schema校验,我们可以使用Java API for XML Processing (JAXP) 提供的工具,特别是SAX或者DOM解析器。SAX解析器是事件驱动的,它逐行解析XML文档并触发相应的事件,如遇到元素开始、元素结束等,...

    JSON Schema 生成库——json-schema-inferrer(java版).rar

    9. **与其他工具的交互**:JSON Schema生成的模型可以与各种工具协同工作,如代码生成器(将Schema转换为Java、JavaScript等语言的类定义),数据验证器(验证JSON数据是否符合Schema),以及文档生成工具(自动生成...

    xml dom,sax解析,schema验证

    XML(eXtensible Markup Language)是一种用于存储和传输数据的标记语言,广泛应用于软件开发、Web...对于初学者,理解DOM和SAX解析的原理,以及如何使用Xerces-C++进行XML Schema验证,是深入学习XML技术的关键步骤。

    json-schema-2.2.6

    在Java开发中,JSON Schema 2.2.6是JSON Schema的一个版本,它包含了对JSON数据验证的详细规则和功能。 JSON Schema 2.2.6的核心概念包括: 1. **模式(Schema)**:这是一个JSON对象,包含了验证规则。例如,你...

    java中Dom验证XMl文件合法非法

    总结来说,Java中的DOM解析器配合XML Schema Factory可以有效地验证XML文件的合法性,通过捕获解析异常和检查返回的`Document`对象来判断验证结果。同时,注意性能优化和安全防护,避免潜在的攻击风险。

    XML Schema教程

    - **在应用程序中使用 XML Schema**:XML Schema 可以用于验证 XML 数据的有效性,确保其符合预期的结构和格式要求。 #### 四、XML Schema 标准 - **XML Schema 是 W3C 标准**:XML Schema 在 2001 年成为了万维网...

    Java EE Schema Resources

    【Java EE Schema Resources】指的是Java企业版(Java Enterprise Edition,简称Java EE)中的模式资源,这些资源主要用于定义和规范Java EE应用的结构和行为。在Java EE开发中,模式资源通常包括XML架构(Schema)...

    java验证字符串是否符合json格式

    对于更严格的验证,可以使用`org.jsonschema2pojo.JsonSchemaValidator`或其他专门的JSON schema验证工具。 在实际开发中,根据项目需求,你可能需要处理不同类型的JSON数据,比如从HTTP响应、文件读取或数据库查询...

    BeanToJsonSchema:Java bean转换为Json Schema

    `BeanToJsonSchema`项目正是为了解决这个问题,它提供了一个功能,能够将Java Bean对象转换成对应的JSON Schema,以便于在JSON数据交换和验证中使用。 JSON Schema的核心特性包括但不限于: 1. **数据类型**:JSON...

    JsonSchema相关jar包

    这个压缩包可能包含了一个或多个Java库,用于在Java应用中执行JSON Schema验证。这些jar包可能是`json-schema-validator`库,例如`com.github.fge.jackson.jsonschema.core.jar`和`...

    根据xml schema生成xml

    2. **验证XML文档**:使用XML解析器或者XML Schema处理器(如Java的JAXB、Apache XMLBeans等)来检查XML文档是否符合XSD的定义。验证过程能发现并报告不符合规范的元素或属性。 3. **根据XML Schema生成XML**:在...

    对xml进行解析;进行增删改查还有schema验证

    使用XML Schema验证,可以避免因数据格式错误导致的问题。在Java中,可以使用`javax.xml.validation`包提供的API进行验证,步骤如下: 1. 加载XML Schema文件:`SchemaFactory.newInstance()`创建`SchemaFactory`...

    \"java xml 二\"之Schema总结

    Java中的`javax.xml.validation`包提供了Schema工厂和验证器,用于生成Schema对象并执行验证。 5. **XML Schema的优点** - 支持复杂数据类型:Schema允许定义更复杂的结构,如嵌套元素和自定义数据类型。 - 强大...

    apache xmlschema api文档

    这些文档能够帮助开发者了解如何在Java程序中导入和使用XML Schema API,从而实现XML文档的解析和验证。 以下是XML Schema API中的几个关键组件和概念: 1. **XMLSchemaFactory**:这是创建XML Schema对象的工厂类...

    (帮助文档大全)javaAPI帮助文档、dom4j帮助文档、Schema帮助文档、XPath文档、DTD帮助文档.rar

    这篇详尽的文章将深入探讨Java API、DOM4J、Schema、XPath和DTD这五个关键的IT概念,这些都是Java开发人员日常工作中不可或缺的知识点。 首先,Java API(Application Programming Interface)是Java编程语言的核心...

Global site tag (gtag.js) - Google Analytics