使用DOM4J解析XML及采用Schema校验的方法

58 篇文章 0 订阅
15 篇文章 1 订阅

使用DOM4J解析XML及采用Schema校验的方法  

Validation 

  Currently dom4j does not come with a validation engine. You are forced to use a external validator (译:dom4j无校验引擎,需使用外部校验). In the past we recommended Xerces,but now you are able to use Sun Multi-Schema XML Validator (原来推荐Xerces,但是现在推荐Sun的复合描述XML校验器) .Xerces is able to validate against DTDs and XML Schema,but not against TREX or Relax. The Suns Multi Schema Validator(MSV) supports all mentioned kinds of validation (Xerces可以按DTDSchema标准解析,但是不能够根据TREXRelax标准解析,Sun的复合描述XML校验器可以支持所有上面提到的校验器).   

  

  Validation consumes valuable resources. Use it wisely.(有选择的使用校验器,下面介绍两种)   

  第一种:Apaches Xerces 1.4.x + dom4j

  Using Apaches Xerces 1.4.x and dom4j for validation 

  It is easy to use Xerces 1.4.x for validation. Download Xerces from Apaches XML web sites. Experience shows that the newest version is not always the best. View Xerces mailing lists in order to find out issues with specific versions. Xerces provides Schema support strarting from 1.4.0.   

  

  Turn on validation mode - which is false for default - using a SAXReader instance (打开SAXReader的校验模式,默认为不打开的) 

  

  Set the following Xerces property http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation using the schema URI. 

  

  以下是校验示例

  Create a SAX XMLErrorHandler and install it to your SAXReader instance.   

  Parse and validate the Document.   

  Output Validation/Parsing errors. 

  

  import org.dom4j.Document; 

  import org.dom4j.Element; 

  import org.dom4j.io.OutputFormat; 

  import org.dom4j.io.SAXReader; 

  import org.dom4j.io.XMLWriter; 

  import org.dom4j.util.XMLErrorHandler; 

  

  

  import org.xml.sax.ErrorHandler; 

  import org.xml.sax.SAXParseException 

  

  public class SimpleValidationDemo { 

  

  public static void main(String[] args) { 

  SAXReader reader = new SAXReader(); 

  

  reader.setValidation(true); 

  

  // specify the schema to use 

  reader.setProperty( 

    "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",

    "prices.xsd" 

  ); 

  

  // add error handler which turns any errors into XML 

    XMLErrorHandler errorHandler = new XMLErrorHandler(); 

    reader.setErrorHandler( errorHandler ); 

  

  // parse the document 

  Document document = reader.read(args[0]); 

  

  // output the errors XML 

  XMLWriter writer = new XMLWriter( OutputFormat.createPrettyPrint() ); 

  writer.write( errorHandler.getErrors() ); 

  } 

  

  

  Both,Xerecs and Crimson,are JaXPable parsers. Be careful while using Crimson and Xerces in same class path. Xerces will work correctly only when it is specified in class path before Crimson. At this time I recommend that you should either Xereces or Crimson.   

  第二种:MSV + dom4j (完美组合)

  A perfect team - Multi Schema ValidatorMSV and dom4j   

  Kohsuke Kawaguchi a developer from Sun created a extremly usefull tool for XML validation. Multi Schema Validator (MSV) supports following specifications:   

  

  Relax NG 

  

  Relax   

  

  TREX 

  

  XML DTDs 

  

  XML Schema 

  

  Currently its not clear whether XML Schema will be the next standard for validation. Relax NG has an ever more growing lobby. If you want to build a open application that is not fixed to a specific XML parser and specific type of XML validation you should use this powerfull tool. As usage of MSV is not trivial the next section shows how to use it in simpler way.   

  

  Simplified Multi-Schema Validation by using Java API for RELAX Verifiers (JARV) 

  The Java API for RELAX Verifiers JARV defines a set of Interfaces and provide a schemata and vendor neutral API for validation of XML documents. The above explained MSV offers a Factory that supports JARV. So you can use the JARV API on top of MSV and dom4j to validate a dom4j documents.   

  

  import org.iso_relax.verifier.Schema; 

  import org.iso_relax.verifier.Verifier; 

  import org.iso_relax.verifier.VerifierFactory; 

  import org.iso_relax.verifier.VerifierHandler; 

  

  import com.sun.msv.verifier.jarv.TheFactoryImpl; 

  

  import org.apache.log4j.Category; 

  

  import org.dom4j.Document; 

  import org.dom4j.io.SAXWriter; 

  

  import org.xml.sax.ErrorHandler; 

  import org.xml.sax.SAXParseException; 

  

  public class Validator { 

  

  private final static CATEGORY = Category.getInstance(Validator.class); 

  private String schemaURI; 

  private Document document; 

  

  public Validator(Document document,String schemaURI) { 

    this.schemaURI = schemaURI; 

    this.document = document; 

  } 

    

  public boolean validate() throws Exception { 

    

    // (1) use autodetection of schemas 

    VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl(); 

    Schema schema = factory.compileSchema( schemaURI ); 

    

    // (2) configure a Vertifier 

    Verifier verifier = schema.newVerifier(); 

      verifier.setErrorHandler( 

          new ErrorHandler() { 

            public void error(SAXParseException saxParseEx) { 

              CATEGORY.error( "Error during validation.",saxParseEx); 

            } 

            

            public void fatalError(SAXParseException saxParseEx) { 

              CATEGORY.fatal( "Fatal error during validation.",saxParseEx); 

            } 

            

            public void warning(SAXParseException saxParseEx) { 

              CATEGORY.warn( saxParseEx ); 

            } 

          } 

      );     

        

    // (3) starting validation by resolving the dom4j document into sax     

    VerifierHandler handler = verifier.getVerifierHandler(); 

    SAXWriter writer = new SAXWriter( handler ); 

    writer.write( document );   

    

    return handler.isValid(); 

  } 

    

  } 

    

  } 

  

  The whole work in the above example is done in validate() method. Foremost the we create a Factory instance and use it to create a JAVR org.iso_relax.verifier.Schema instance. In second step we create and configure a org.iso_relax.verifier.Verifier using a org.sax.ErrorHandler. I use Apaches Log4j API to log possible errors. You can also use System.out.println() or,depending of the applications desired robustness,any other method to provide information about failures. Third and last step resolves the org.dom4j.Document instance using SAX in order to start the validation. Finally we return a boolean value that informs about success of the validation.   

  

  Using teamwork of dom4j,MSV,JAVR and good old SAX simplifies the usage of multi schemata validation while gaining the power of MSV.   

  

  XSLT defines a declarative rule-based way to transform XML tree into plain text,HTML,FO or any other text-based format. XSLT is very powerful. Ironically it does not need variables to hold data. As Michael Kay XSLTReference says: "This style of coding without assignment statements,is called Functional Programming. The earliest and most famous functional programming language was Lisp ...,while modern examples include ML and Scheme." In XSLT you define a so called template that matches a certain XPath expression. The XSLT Processor traverse the source tree using a recursive tree descent algorithm and performs the commands you defined when a specific tree branch matches the template rule.   

  

  dom4j offers an API that supports XSLT similar rule based processing. The API can be found in org.dom4j.rule package and this chapter will introduce you to this powerful feature of dom4j.   

如果文章对你用,请支持万事如意网址导航

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 使用 Java 语言编写程序来校验 JSON Schema 是非常容易的,可以使用许多库和框架来帮助您实现它。有许多第三方库和框架可以用于校验 JSON 格式,这些库和框架包括:Jackson,Gson,Genson,Apache Commons,Hibernate Validator,JsonSchema,JsonPath 和 FastJSON。 ### 回答2: 在Java中,可以使用现有的库来编写代码,使用jsonSchema校验数据。下面是使用Java编写的示例代码: 首先,需要导入相关的依赖库,例如使用Jackson库来处理JSON数据和使用json-schema-validator库来执行jsonSchema校验。可以通过Maven或Gradle等构建工具来管理依赖。 接下来,创建一个方法来执行校验操作。首先,需要定义jsonSchema的规则,可以使用JSON字符串或从外部文件中加载。然后,需要将待校验的数据转换为JSON对象,可以使用Jackson库将字符串解析为JSON对象。 然后,使用json-schema-validator库中的JsonSchemaFactory类来创建JsonSchema实例。使用JsonSchema的validate方法对JSON数据进行校验,该方法会返回校验结果。 最后,根据校验结果进行相应的处理,可以输出校验失败的原因或执行其他操作。 以下是一个简单的示例代码: ```java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.fge.jsonschema.core.exceptions.ProcessingException; import com.github.fge.jsonschema.core.report.ProcessingReport; import com.github.fge.jsonschema.main.JsonSchema; import com.github.fge.jsonschema.main.JsonSchemaFactory; public class JsonValidator { public static void main(String[] args) { String schema = "{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" } } }"; String data = "{ \"name\": \"John\" }"; boolean isValid = validateData(schema, data); if (isValid) { System.out.println("Data is valid."); } else { System.out.println("Data is invalid."); } } public static boolean validateData(String schemaString, String dataString) { ObjectMapper objectMapper = new ObjectMapper(); JsonNode schemaNode, dataNode; try { schemaNode = objectMapper.readTree(schemaString); dataNode = objectMapper.readTree(dataString); } catch (Exception e) { e.printStackTrace(); return false; } JsonSchemaFactory schemaFactory = JsonSchemaFactory.byDefault(); try { JsonSchema schema = schemaFactory.getJsonSchema(schemaNode); ProcessingReport report = schema.validate(dataNode); return report.isSuccess(); } catch (ProcessingException e) { e.printStackTrace(); return false; } } } ``` 以上代码使用了Jackson库将schema和数据解析为JSON节点,然后使用json-schema-validator库来创建JsonSchema对象,并使用validate方法进行校验。最后根据校验结果输出相应的信息。 当运行以上代码时,如果数据满足schema的定义,会输出"Data is valid.",否则输出"Data is invalid."。这个示例中使用了简单的schema和数据进行校验,实际使用中可以根据需要定义更复杂的schema,并使用更复杂的校验逻辑。 ### 回答3: 使用Java编写可以使用以下步骤来使用jsonSchema校验数据。 首先,你需要引入json-schema-validator库。你可以在Maven或Gradle中添加以下依赖项: 对于Maven: ```xml <dependency> <groupId>org.everit.json</groupId> <artifactId>org.everit.json.schema</artifactId> <version>1.12.1</version> </dependency> ``` 对于Gradle: ```groovy implementation 'org.everit.json:org.everit.json.schema:1.12.1' ``` 接下来,你需要创建一个json schema的字符串或从文件中读取json schema。假设你有以下的json schema字符串: ```json String schemaStr = "{\n" + " \"type\": \"object\",\n" + " \"properties\": {\n" + " \"name\": {\n" + " \"type\": \"string\"\n" + " },\n" + " \"age\": {\n" + " \"type\": \"integer\"\n" + " }\n" + " },\n" + " \"required\": [\"name\", \"age\"]\n" + "}"; ``` 然后你可以使用下面的代码来校验数据: ```java import org.everit.json.schema.Schema; import org.everit.json.schema.ValidationException; import org.everit.json.schema.loader.SchemaLoader; import org.json.JSONObject; import org.json.JSONTokener; class Main { public static void main(String[] args) { String dataStr = "{\"name\":\"John\", \"age\":30}"; try { JSONObject jsonSchema = new JSONObject(new JSONTokener(schemaStr)); JSONObject jsonData = new JSONObject(new JSONTokener(dataStr)); Schema schema = SchemaLoader.load(jsonSchema); schema.validate(jsonData); System.out.println("数据是有效的"); } catch (ValidationException e) { System.out.println("数据无效:" + e.getMessage()); } } } ``` 以上代码将创建一个Schema对象,并使用Schema.validate方法来验证数据。如果数据有效,将输出“数据是有效的”,否则将输出"数据无效"及详细错误信息。 这就是使用Java编写jsonSchema校验数据的基本步骤。你可以根据自己的需求修改json schema和数据,并在代码中进行相应的处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值