-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathXMLValidator.java
More file actions
97 lines (82 loc) · 1.85 KB
/
XMLValidator.java
File metadata and controls
97 lines (82 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package de.binfalse.martin;
import java.io.File;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
/**
* The XMLValidator to validate XML files.
*
* @author martin scharm
*/
public class XMLValidator
{
/** The validator. */
Validator validator;
/**
* Instantiates a new XML validator.
*
* @param schemaFile
* the schema file
* @throws SAXException
*/
public XMLValidator (File schemaFile) throws SAXException
{
validator = SchemaFactory.newInstance ("http://www.w3.org/2001/XMLSchema")
.newSchema (schemaFile).newValidator ();
}
/**
* Validate a file.
*
* @param xmlFile
* the XML file to validate
* @return true, if file is valid
*/
public boolean validateFile (File xmlFile)
{
try
{
Source source = new StreamSource (xmlFile);
long time = System.currentTimeMillis ();
validator.validate (source);
time = System.currentTimeMillis () - time;
System.out.println ("took: " + time / 1000 + "s");
return true;
}
catch (Exception e)
{
e.printStackTrace ();
}
return false;
}
/**
* The main method for testing purposes.
*
* @param args
* the arguments
*/
public static void main (String[] args)
{
args = new String[] { "/tmp/schema.xsd", "/tmp/testfile.xml" };
try
{
System.out.println ("creating val");
XMLValidator validator = new XMLValidator (new File (args[0]));
System.out.println ("validating");
if (validator.validateFile (new File (args[1])))
{
System.out.println ("file is valid!");
return;
}
else
System.out.println ("file is invalid!");
}
catch (SAXException e)
{
System.out.println ("sax error:");
e.printStackTrace ();
}
System.exit (1);
}
}