XML与XSD两兄弟

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013310119/article/details/88239760

一、简单描述(总体)

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 例如:

<?xml version="1.0" encoding="UTF-8"?>
<service xmlns="http://www.tax.inspur.com/shdbkfpt/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.tax.inspur.com/shdbkfpt/ Request_00001.xsd">
<head>
<tran_id>SHXXPT.DBZXAPI.CX.XYXX</tran_id>
<channel_id>SHXXPT.CREDITSWAP.CXW.XYINFO</channel_id>
<tran_seq>1cc853d50ce74b1bacb564b8e30f0385</tran_seq>
<tran_date>2019-03-06</tran_date>
<tran_time>16:19:35</tran_time>
<expand>
<name>sjly</name>
<value>shyh</value>
</expand>
<expand>
<name>identification</name>
<value>6516a66d-b598-11e8-bbc9-00ffda4b0b43</value>
</expand>
</head>
<body><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<taxINSPUR xsi:type="Request_00001" xmlns="http://www.tax.inspur.com/shdbkfpt/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.tax.inspur.com/shdbkfpt/ Request_00001.xsd">
<queryHonestData>
<nsrmc>11111</nsrmc>
<shxydm>987654321234556</shxydm>
<ssdq>511601</ssdq>
<paging>
<pageSize>10</pageSize>
<pageIndex>1</pageIndex>
</paging>
</queryHonestData></taxINSPUR>
]]></body>
</service>

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

<?xml version="1.0" encoding="utf-16"?>
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="service">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="head">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element name="tran_id" type="xsd:string" />
              <xsd:element name="channel_id" type="xsd:string" />
              <xsd:element name="tran_seq" type="xsd:string" />
              <xsd:element name="tran_date" type="xsd:dateTime" />
              <xsd:element name="tran_time" type="xsd:dateTime" />
              <xsd:element name="expand">
                <xsd:complexType>
                  <xsd:sequence>
                    <xsd:element name="name" type="xsd:string" />
                    <xsd:element name="value" type="xsd:string" />
                  </xsd:sequence>
                </xsd:complexType>
              </xsd:element>
            </xsd:sequence>
          </xsd:complexType>
        </xsd:element>
        <xsd:element name="body" type="xsd:string" />
      </xsd:sequence>
      <xsd:attribute name="xsi:schemaLocation" type="xsd:string" />
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

新增文件保存为 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<String> IPs = new ArrayList<String>();
	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;
	}
	
	/**
	 * <form class="form-add" enctype="multipart/form-data">
	 * <bean id="multipartResolver"></bean>
	 * 使用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<String> getIPs() {
		ArrayList<String> ips = new ArrayList<String>();
		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<String> getServerIPs() {
		return IPs;
	}
}

猜你喜欢

转载自blog.csdn.net/u013310119/article/details/88239760