现在的位置: 首页 > 综合 > 正文

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

2014年01月15日 ⁄ 综合 ⁄ 共 7237字 ⁄ 字号 评论关闭

使用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.   

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

抱歉!评论已关闭.