Ant: XML Schema Validation of a Directory Tree
Ant provides a very convenient task for validating all the files in a directory or directory tree. You can use the xmlvalidate
task to validate an XML file, or using a fileset
, all the files in a directory or directory tree.
Here is an example build.xml file:
Listing for build.xml
1:<project name="project1" default="validate_project_files"> 2: 3: <target name="validate_project_files"> 4: <!-- Make sure the files are valid --> 5: <xmlvalidate failonerror="yes" lenient="no" warn="yes" 6: classname="org.apache.xerces.parsers.SAXParser" 7: classpath="lib/xerces.jar" 8: > 9: <fileset dir="." includes="**/*.xml"/> 10: <attribute name="http://xml.org/sax/features/validation" value="true"/> 11: <attribute name="http://apache.org/xml/features/validation/schema" value="true"/> 12: </xmlvalidate> 13: <echo message="Project files have been validated" /> 14: </target> 15:</project>
A few thoughts on the build file:
- The attribute
lenient
is set to no so that the files will be validated. Setting the value to yes will only check the files for well formedness. - Setting the attributes
classname
andclasspath
are optional according to the documentation. However, I ran into some problems when these attributes were not set. See this how to. - The
fileset
allows you to validate all the files in a directory or a directory tree. - The attribute elements inside the
xmlvalidate
tag enable XML schema validation for the Xerces parser. Schema validation is not enabled by default. - The
echo
message on line 13 was added to display a message when things go well.