Many times our applications or Web programs need to be configured with XML files, and the final program needs to be used by the client, so the XML or client is required to write, and when the client writes, it doesn't guarantee that the XML file is absolutely correct, so I wrote this class, The main function is to verify that the XML writing file conforms to the defined XSD specification.
Package common.xml.validator;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.Reader;
Import Java.io.StringReader;
Import Java.net.URL;
Import javax.xml.XMLConstants;
Import Javax.xml.transform.Source;
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;
/** *//**
* @author Suyuan
*
*/
public class XmlSchemaValidator {
Private Boolean isValid = true;
Private String Xmlerr = "";
public Boolean isValid () {
return isValid;
}
Public String Getxmlerr () {
return xmlerr;
}
Public XmlSchemaValidator ()
{
}
public boolean Validxmldoc (String xml,url Schema)
{
StringReader reader = new StringReader (XML);
Return Validxmldoc (Reader,schema);
}
public boolean Validxmldoc (Reader xml,url Schema)
{
try {
InputStream Schemastream = Schema.openstream ();
Source Xmlsource = new Streamsource (XML);
Source Schemasource = new Streamsource (schemastream);
Return Validxmldoc (Xmlsource,schemasource);
catch (IOException e) {
IsValid = false;
Xmlerr = E.getmessage ();
return false;
}
}
public boolean Validxmldoc (String xml,file Schema)
{
StringReader reader = new StringReader (XML);
Return Validxmldoc (Reader,schema);
}
public boolean Validxmldoc (Reader xml,file Schema)
{
try {
FileInputStream Schemastream = new FileInputStream (schema);
Source Xmlsource = new Streamsource (XML);
Source Schemasource = new Streamsource (schemastream);
Return Validxmldoc (Xmlsource,schemasource);
catch (IOException e) {
IsValid = false;
Xmlerr = E.getmessage ();
return false;
}
}
public boolean Validxmldoc (Source xml,source schemasource)
{
try {schemafactory schemafactory = schemafactory.newinstance (Xmlconstants.w3c_xml_schema_ns_uri);
if (xml==null| | Xml.equals (""))
{
return false;
}
Schema schema = Schemafactory.newschema (Schemasource);
Validator valid = Schema.newvalidator ();
Valid.validate (XML);
return true;
catch (Saxexception e) {
IsValid = false;
Xmlerr = E.getmessage ();
return false;
}
catch (IOException e) {
IsValid = false;
Xmlerr = E.getmessage ();
return false;
}
catch (Exception e) {
IsValid = false;
Xmlerr = E.getmessage ();
return false;
}
}
}