Validation of XML files in Java

Source: Internet
Author: User
Tags xml parser

Use DTD to validate XML files in Java:

1. Define a Check class Checkxml class:

Import org.w3c.dom.Document;

Import Org.xml.sax.EntityResolver;
Import Org.xml.sax.ErrorHandler;
Import Org.xml.sax.InputSource;
Import org.xml.sax.SAXException;
Import org.xml.sax.SAXParseException;

Import java.io.IOException;
Import Java.io.InputStream;
Import Java.net.URL;

Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import javax.xml.parsers.ParserConfigurationException;

public class Checkxml () {

Public Doucment Getcheckxml () {

list<studentuao> result = new arraylist<> ();

Use the Java ClassLoader to find the resource file under the classpath.

1. Gets the object of any class type, the class name. Classes can return a class object.

class<?> clazz = Teststudent.class;

2. Call getResourceAsStream (arg0) to get the input stream.

Look for a file named Book.xml from the root of the classpath.

Automatically finds a file named Student.xml under all Classpath, returns immediately after finding the first one, and does not continue looking.

URL url = Clazz.getresource ("./student.xml");

The following is the root directory of the output Student.xml file

System.out.println (URL);

InputStream in = Url.openstream ();

1. Create Documentbuilderfactory

Documentbuilderfactory builderfactory = Documentbuilderfactory.newinstance ();

Turn on validation!

Builderfactory.setvalidating (TRUE);

2. Create Documentbuilder with Documentbuilderfactory

Documentbuilder builder = Builderfactory.newdocumentbuilder ();

3. Use Entityresolver to tell the XML parser where the DTD file is!

Also under the classpath of the current class, look for the Student.dtd file

Builder.setentityresolver (New Entityresolver () {

@Override

Public InputSource resolveentity (string arg0, String arg1) throws Saxexception, IOException {

InputStream Dtdstream = Clazz.getresourceasstream ("./student.dtd");

InputSource Source = new InputSource (dtdstream);

return source;

}

});

4. In order to be able to obtain the accurate analysis verification information, must provide a ErrorHandler

MyErrorHandler eh = new MyErrorHandler ();

Builder.seterrorhandler (EH);

if (Eh.issucceed ()) {

System.out.println ("Parse success! ");

5. Execution resolution

The bottom layer reads the XML content using sax, so the read performance is better

Document doc = Builder.parse (in);

return doc;

}else{

System.out.println ("Parse failed! ");

return null;

}

}

Static Class MyErrorHandler implements ErrorHandler {

Private Integer errorcount = 0;

@Override

public void error (Saxparseexception arg0) throws Saxexception {

System.out.println ("There is an error! ");

Arg0.printstacktrace (System.out);

errorcount++; }

@Override

public void FatalError (Saxparseexception arg0) throws Saxexception {

SYSTEM.OUT.PRINTLN ("A fatal error has occurred! ");

Arg0.printstacktrace (System.out);

errorcount++; }

@Override

public void Warning (saxparseexception arg0) throws Saxexception {

System.out.println ("Warning appears! ");

Arg0.printstacktrace (System.out); }

Determine if the resolution is successful!

public Boolean issucceed () {if (Errorcount = = 0) {return true;   } return false; }  }

}

1.2DOM4J using DTD checksum xml:

1. Create Saxreader Saxreader reader = new Saxreader ();

2. Turn on Verify reader.setvalidation (true);

3. Set Entityresolver, in dom4j, the default to find the same directory of the DTD file/

/Provide the reason for the setentityresolver, mainly to solve: if the XML declaration of the DTD file and the actual DTD file name is different, can correctly find the DTD

Reader.setentityresolver (New Entityresolver () {

@Override

Public InputSource resolveentity (string publicid, String systemid) throws Saxexception, IOException {

URL Dtdurl = Cla.getresource ("./students.dtd");

InputStream Dtdstream = Dtdurl.openstream ();

InputSource Source = new InputSource (dtdstream);

return source; }   });

4. Read the XML to generate the Document object
Document document = Reader.read (URL);

==============================================

Java uses schame to validate XML files:

2.1 Create a VALIDATIONXM class:

Import java.io.IOException;

Import Java.io.InputStream;

Import Java.net.URL;

Import javax.xml.XMLConstants;

Import Javax.xml.transform.stream.StreamSource;

Import Javax.xml.validation.Schema; Import Javax.xml.validation.SchemaFactory;

Import Javax.xml.validation.Validator;

Import org.xml.sax.SAXException;

public class Validationxml {

public static void Getvalidationxml () throws Saxexception, IOException {

URL url = ValidationXML.class.getResource ("book.xsd");

Reading the schema file

Schema s = schemafactory.newinstance (Xmlconstants.w3c_xml_schema_ns_uri). Newschema (URL);

Creating validators

Validator v = s.newvalidator ();

Validating an input stream

InputStream in = ValidationXML.class.getResourceAsStream ("/book.xml");

Streamsource Source = new Streamsource (in);

V.validate (source);

Verify no error to read

...--------------();

} }

3. Use dom4j: Two packages required: Dom4j.jar,jaxen-1.1-beta-6.jar.

Import java.io.IOException;

Import Java.io.InputStream;

Import org.dom4j.Document;

Import org.dom4j.DocumentException;

Import Org.dom4j.io.SAXReader;

Import Org.xml.sax.EntityResolver;

Import Org.xml.sax.InputSource;

Import org.xml.sax.SAXException;

public class Validatingdom4j {

public static void Main (string[] args) throws Documentexception,

saxexception {

Saxreader reader = new Saxreader ();

Turn on validation

Reader.setvalidation (TRUE);

Validates the specified input.

Reader.setfeature ("Http://apache.org/xml/features/validation/schema", true);

Locate the XSD file location reader.setentityresolver (new Entityresolver () {

@Override

Public InputSource resolveentity (string publicid, String systemid) throws Saxexception, IOException {

InputStream in = Validatingdom4j.class. getResourceAsStream ("book.xsd");

InputSource Source = new InputSource (in);

return source; }

});

InputStream in = ValidatingDom4j.class.getResourceAsStream ("Book.xml");

Document doc = Reader.read (in); } }

Validation of XML files in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.