XmlTools.java
2.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.tianbo.analysis.tools;
import lombok.extern.slf4j.Slf4j;
import org.xml.sax.SAXException;
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 java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
/**
* @author mrz
* @date 20220110
* XML相关工具类
*/
@Slf4j
public class XmlTools {
/**
* 根据XSD校验XML报文是否正确
* @param xsdPath xsd文件路径
* @param xmlStr xml报文内容
* @return 正确错误
* @throws IOException 文件读取解析异常
*/
public static boolean validateXMLSchema(String xsdPath, String xmlStr) throws IOException,SAXException {
ByteArrayInputStream bais = new ByteArrayInputStream(xmlStr.getBytes("UTF-8"));
try {
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File(xsdPath));
Validator validator = schema.newValidator();
Source source = new StreamSource(bais);
validator.validate(source);
} catch (IOException | SAXException e) {
e.printStackTrace();
log.error("Exception:{}",e.getMessage());
return false;
}finally {
bais.close();
}
return true;
}
public static boolean validateXMLSchemaThrowError(String xsdPath, String xmlStr) throws IOException,SAXException {
ByteArrayInputStream bais = new ByteArrayInputStream(xmlStr.getBytes("UTF-8"));
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File(xsdPath));
Validator validator = schema.newValidator();
Source source = new StreamSource(bais);
validator.validate(source);
return true;
}
}