XML与XSD两兄弟

一、简单描述(总体)

XML Schema描述了XML文档的结构。可以用一个指定的XML Schema来验证某个XML文档,以检查该XML文档是否符合其要求。文档设计者可以通过XML Schema指定一个XML文档所允许的结构和内容,并可据此检查一个XML文档是否是有效的。XML Schema本身是一个XML文档,它符合XML语法结构。可以用通用的XML解析器解析它。
    一个XML Schema会定义:文档中出现的元素、文档中出现的属性、子元素、子元素的数量、子元素的顺序、元素是否为空、元素和属性的数据类型、元素或属性的默认和固定值。

       简而言之,XSD文件用来定义Xml的格式的文件,而XML是按照一定的Xsd格式生成的数据文档。  
 

二、利用XML生成XSD文件

第一种方法

首先拿到xml 例如:




SHXXPT.DBZXAPI.CX.XYXX
SHXXPT.CREDITSWAP.CXW.XYINFO
1cc853d50ce74b1bacb564b8e30f0385
2019-03-06
16:19:35

sjly
shyh


identification
6516a66d-b598-11e8-bbc9-00ffda4b0b43





11111
987654321234556
511601

10
1


]]>

通过:http://www.xmlforasp.net/CodeBank/System_Xml_Schema/BuildSchema/BuildXMLSchema.aspx 这个网站在线转成xsd



  
    
      
        
          
            
              
              
              
              
              
              
                
                  
                    
                    
                  
                
              
            
          
        
        
      
      
    
  

新增文件保存为 test.xsd 编码utf-16 改成utf-8

cmd 进入到文件下执行:

xjc test.xsd -p test.java

然后就可以看到生成的文件了,  就是这么的简单;

三、在JAVA项目实际应用中,如何对XML 进行Schema 验证的方法

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.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.****.tax.yh.util.WebInfo;

public class XMLValidation {
	static String context = WebInfo.getRealPath();
	static String xmlPath = "/WEB-INF/classes/com/inspur/tax/shdbkfpt/webservice/xsd/";

	public static String validateHead(String xmlString) {

		try {
			SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
			Schema schema = factory.newSchema(new File(context+xmlPath+"common/Request_head.xsd"));
			Validator validator = schema.newValidator();
			validator.validate(new StreamSource(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))));
		} catch (Exception e) {
			return e.getMessage();
		}
		return "true";
	}
	
	public static String validateBody(String xmlString) throws Exception {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new ByteArrayInputStream(xmlString.getBytes("UTF-8")));
		Element root = doc.getRootElement();
		String xsi_type = root.attributeValue("type");
		if(xsi_type.contains("../")||xsi_type.contains("..\\")){
			return "非法的xsi:type!";
		}
		try {
			SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
			Schema schema = factory.newSchema(new File(context+xmlPath+xsi_type+".xsd"));
			Validator validator = schema.newValidator();
			validator.validate(new StreamSource(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))));
		} catch (Exception e) {
			return e.getMessage();
		}
		return "true";
	}
}
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.loushang.ws.context.MessageContext;
import org.loushang.ws.transport.http.HTTPConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class WebInfo {
	private static ArrayList IPs = new ArrayList();
	private static String realPath;
	private static String contextPath;
	private static boolean initialized = false;

	private static final Logger LOGGER = LoggerFactory.getLogger(WebInfo.class);

	public static void init(ServletContext servletContext) {
		if (initialized){
			return;
		}
		realPath = convertPath(servletContext.getRealPath(""), false);
		contextPath = convertPath(servletContext.getContextPath(), false);
		IPs = getIPs();
		initialized = true;
	}
	
	/**
	 * 
* * 使用MultipartHttpServletRequest后,即上述配置,该方法获取不到parameter值 * @return * @return HttpServletRequest */ public static HttpServletRequest getRequest() { ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder .getRequestAttributes(); HttpServletRequest httpServletRequest = null; if (servletRequestAttributes != null) { httpServletRequest = servletRequestAttributes.getRequest(); } else { MessageContext mc = MessageContext.getCurrentMessageContext(); if (mc != null) { httpServletRequest = (HttpServletRequest) mc.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); } } return httpServletRequest; } private static ArrayList getIPs() { ArrayList ips = new ArrayList(); try { Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface interfaceN = (NetworkInterface) interfaces.nextElement(); Enumeration ienum = interfaceN.getInetAddresses(); while (ienum.hasMoreElements()) { InetAddress ia = (InetAddress) ienum.nextElement(); String adress = ia.getHostAddress().toString(); if ((adress.length() > 16) || (adress.startsWith("127")) || (adress.indexOf(":") > 0)) { continue; } ips.add(adress); } } } catch (Exception e) { LOGGER.error("获取本机IP异常!"); } return ips; } private static String convertPath(String path, boolean fix) { if ((path == null) || (path.length() == 0)) { return path; } path = path.replace("\\", "/"); if (!fix && (path.endsWith("/"))) { path = path.substring(0,path.length()-1); }else if (fix && (!(path.endsWith("/")))) { path = path + "/"; } return path; } public static String getClientIp(HttpServletRequest request) { String ipAddress = request.getHeader("x-forwarded-for"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) { // 根据网卡取本机配置的IP InetAddress inet = null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ipAddress = inet.getHostAddress(); } } // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() // = 15 if (ipAddress.indexOf(",") > 0) { ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); } } return ipAddress; } public static String getRealPath() { return realPath; } public static String getContextPath() { return contextPath; } public static ArrayList getServerIPs() { return IPs; } }

 

你可能感兴趣的:(工具)