jdom实现schema验证xml文件是否合法
导入jdom1.1版
http://www.jdom.org/dist/binary/
import java.io.FileReader;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;
public class XMLValidate {
public void validate(String xml, String schema) {
try {
SAXBuilder builder = new SAXBuilder(true);
//指定约束方式为XML schema
builder.setFeature("http://apache.org/xml/features/validation/schema",true);
//导入schema文件
builder.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",schema);
Document doc = builder.build(new FileReader(xml));
System.out.println("恭喜您,验证通过!!!");
}catch(Exception e) {
System.out.println("验证失败:"+e);
}
}
public static void main(String args[]) {
new XMLValidate().validate("e:\\a.xml","e:\\b.xsd");
}
}
老版本需要用到Xerces
参见http://www.jdom.org/docs/faq.html#a0360
How do I validate against a schema when using JDOM?
JDOM doesn't have it's own parser; it uses standard parsers like Xerces to do the heavy lifting. If you want schema validation make sure you choose a parser that supports schemas. Xerces 2 is a good choice (get it from http://xml.apache.org). You also need to use code JDOM Beta 8 or later.
To specify the parser JDOM uses, you can either configure JAXP appropriately (since JDOM uses JAXP if it's available, see the end of this entry for details) or you can explicitly pass the name of the parser to the SAXBuilder constructor. For Xerces 2 the parser class is org.apache.xerces.parsers.SAXParser. You must also enable parser validation by passing "true" when creating a SAXBuilder.
SAXBuilder builder =
new SAXBuilder("org.apache.xerces.parsers.SAXParser", true);
Next, you tell the parser (Xerces) you want to validate against a schema (or schemas), and you pass the parser information about those schema. Different parsers do this in different ways. In Xerces you do this by
相关文档:
精短高效的XML解析器,纯C单一程序,应用于银行的国税库行横向联网接口系统中,稳定可靠,运行速度飞快,非相应的JAVA程序可比.以下为大部分源码:
/* Copyright (c) 2005 wzs */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <varargs.h>
#i ......
<
<
小于
>
>
大于
&
&
和号
'
'
单引号
"
"
引号
注释:在 XML 中,只有字符 "<" 和 "&" 确实是非法的。大于号是合法的,但是用实体引用来代替它是一个好习惯。 ......
转自http://www0.ccidnet.com/tech/guide/2001/10/08/58_3392.html
SAX概念
SAX是Simple API for XML的缩写,它并不是由W3C官方所提出的标准,可以说是“民间”的事实标准。实际上,它是一种社区性质的讨论产物。虽然如此,在XML中对SAX的应用丝毫不比DOM少,几乎所有的XML解析器都会支持它。
与DOM比较而言 ......
SAX概念
SAX是Simple API for XML的缩写,它并不是由W3C官方所提出的标准,可以说是“民间”的事实标准。实际上,它是一种社区性质的讨论产物。虽然如此,在XML中对SAX的应用丝毫不比DOM少,几乎所有的XML解析器都会支持它。
与DOM比较而言,SAX是一种轻量型的方法。我们知道,在处理DOM的时候,我们需要读 ......
1. 下载与安装
dom4j是sourceforge.net上的一个开源项目,主要用于对XML的解析。从2001年7月发布第一版以来,已陆续推出多个版本,目前最高版本为1.5。
dom4j专门针对Java开发,使用起来非常简单、直观, ......