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("
分享一个java通过xsd(字符串)校验xml(字符串)的方法
于 2022-05-18 15:49:24 首次发布