Java : use xsd 校验 xml

本文提供了一个使用Java进行XML Schema验证的示例程序。通过该程序可以了解如何利用W3C XML Schema语言来验证XML文件的有效性。示例中包含了创建验证器、加载Schema文件并检查目标XML文件的具体步骤。
 1 import javax.xml.parsers.DocumentBuilder;
 2 import javax.xml.parsers.DocumentBuilderFactory;
 3 
 4 import org.w3c.dom.Document;
 5 import org.xml.sax.ErrorHandler;
 6 import org.xml.sax.InputSource;
 7 import org.xml.sax.SAXException;
 8 import org.xml.sax.SAXParseException;
 9 
10 import java.io.*;
11 import javax.xml.transform.Source;
12 import javax.xml.transform.stream.StreamSource;
13 import javax.xml.validation.*;
14 import org.xml.sax.SAXException;
15 
16 public class XValidator {
17 
18     /**
19      * @param args
20      */
21     public static void main(String[] args) throws SAXException, IOException {
22 
23         System.out.println("Validation file: "+ args[1]);
24         System.out.println("with: "+ args[0]);
25         System.out.println();
26         // 1. Lookup a factory for the W3C XML Schema language
27         SchemaFactory factory = 
28             SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
29         
30         // 2. Compile the schema. 
31         // Here the schema is loaded from a java.io.File, but you could use 
32         // a java.net.URL or a javax.xml.transform.Source instead.
33         File schemaLocation = new File(args[0]);
34         Schema schema = factory.newSchema(schemaLocation);
35     
36         // 3. Get a validator from the schema.
37         Validator validator = schema.newValidator();
38         
39         // 4. Parse the document you want to check.
40         Source source = new StreamSource(args[1]);
41         
42         // 5. Check the document
43         try {
44             validator.validate(source);
45             System.out.println(args[0] + " is valid.");
46         }
47         catch (SAXException ex) {
48             System.out.println("Error: " + args[0] + " is not valid because: ");
49             System.out.println(ex.getMessage());
50         }  
51         
52     }
53 
54 }
55 class SimpleErrorHandler implements ErrorHandler{
56 
57     @Override
58     public void error(SAXParseException arg0) throws SAXException {
59         System.out.printf("error=%s\n", arg0.getMessage());
60     }
61 
62     @Override
63     public void fatalError(SAXParseException arg0) throws SAXException {
64         System.out.printf("fatalError=%s\n", arg0.getMessage());
65         
66     }
67 
68     @Override
69     public void warning(SAXParseException arg0) throws SAXException {
70         System.out.printf("warning=%s\n", arg0.getMessage());
71         
72     }
73     
74 }

转载于:https://www.cnblogs.com/sliencer/archive/2012/03/25/2416713.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值