package com.bringspring.project.tool.jsonScheme.util;
import org.apache.camel.StringSource;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXValidator;
import org.dom4j.io.XMLWriter;
import org.dom4j.util.XMLErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
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 java.io.*;
public class checkXML {
public static String validateXMLByXSD(String xmlContent, String xsdContent) throws SAXException {
String result = "";
//创建SchemaFactory工厂
SchemaFactory sch=SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Source source = new StringSource(xmlContent);
//s = s.replaceAll(" ","");
Source source1 = new StringSource(xsdContent);
//利用SchemaFactory工厂对象,接收验证的文件对象,生成Schema对象
Schema schema=sch.newSchema(source1);
//产生对此schema的验证器
Validator validator=schema.newValidator();
//开始验证
try {
validator.validate(source);
result = "成功";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("失败");
result = "失败";
}
return result;
}
public static void main(String[] args) throws FileNotFoundException, SAXException {
//test
String xmlContent = "n" +
"n" +
"n" +
"n" +
" n" +
"n" +
" 172-32-1176n" +
"n" +
" Whiten" +
"n" +
" Johnsonn" +
"n" +
" 408 496-7223n" +
"n" +
" 10932 Bigge Rd.n" +
"n" +
" Menlo Parkn" +
"n" +
" CAn" +
"n" +
" 94025n" +
"n" +
" truen" +
"n" +
" n" +
"n" +
" n" +
"n" +
" 213-46-8915n" +
"n" +
" Greenn" +
"n" +
" Marjorien" +
"n" +
" 415 986-7020n" +
"n" +
" 309 63rd St. #411n" +
"n" +
" Oaklandn" +
"n" +
" CAn" +
"n" +
" 94618n" +
"n" +
" truen" +
"n" +
" n" +
"n" +
"";
String xsdContent = "n" +
"n" +
"n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
" n" +
"n" +
"";
String result1 = validateXMLByXSD(xmlContent, xsdContent);
System.out.println(result1);
}
}