Java XSD验证XML的方法总结

网上流传着很多XSD验证XML是否正确的方法,XSD是DTD的替代者。

用javax.xml.validation.Validator.validate(Source source)应该是最快捷方法的 

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

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 org.xml.sax.SAXException;

/**
 * 校验xml工具类
 */
public class ValidateXML {
	private ValidateXML() {
		throw new Error("工具类不允许实例化");
	}
	public static boolean validateXML(String xsdPath, String xmlData) {
		// 建立schema工厂
		SchemaFactory schemaFactory = SchemaFactory
				.newInstance("http://www.w3.org/2001/XMLSchema");
		// 建立验证文档文件对象,利用此文件对象所封装的文件进行schema验证
		File schemaFile = new File(xsdPath);
		// 利用schema工厂,接收验证文档文件对象生成Schema对象
		Schema schema = null;
		try {
			schema = schemaFactory.newSchema(schemaFile);
		} catch (SAXException e) {
			e.printStackTrace();
		}
		// 通过Schema产生针对于此Schema的验证器,利用schenaFile进行验证
		Validator validator = schema.newValidator();
		// 得到验证的数据源
		Source source = new StreamSource(String2InputStream(xmlData));
		// 开始验证,成功输出success!!!,失败输出fail
		// 参数还可以用文件的String转为的inputstreamnew
		// ByteArrayInputStream(text.getBytes("UTF-8"));
		try {
			validator.validate(source);
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * 将字符串转换为流对象
	 * @param str
	 *            需要装的字符串
	 * @return 返回流对象
	 * @since CodingExample Ver(编码范例查看) 1.1
	 */
	private static InputStream String2InputStream(String str) {
		ByteArrayInputStream stream = null;
		try {
			stream = new ByteArrayInputStream(str.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return stream;
	}
}

【2】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值