Apache Ant/XMLwellformed

From Wikibooks, open books for an open world
Jump to: navigation, search

You can use Apache ant to check a file or group of files for well-formedness. This is different from validation. Checking for well formedness simply checks for the consistency of begin and end tags. No XML Schema file is used.

This is done by using the <xmlvalidate> task. The xmlvalidate ant task will use a standard ant <fileset> and go through each file. In the example below, we specify a directory called "in" using a property. We then use the fileset to find all XML files in that directory and all subdirectories of that directory.

<project default="CheckXML">

   <property name="MYROOTDIR" value="in"/>
   <target name="CheckXML" description="Checks that all files at or below MYROOTDIR are well formed">
     <xmlvalidate>
        <fileset dir="${MYROOTDIR}" includes="**/*.xml"/>
        <attribute name="http://xml.org/sax/features/validation" value="false"/>
        <attribute name="http://apache.org/xml/features/validation/schema"  value="false"/>
     </xmlvalidate>
   </target>
 
 </project>

This target will run the default XML parser that comes with Ant (usually Xerces) and report any file that is not well-formed.

To test this example, add a folder called "in" and put several XML files in the folder that are malformed. In this case we created a mal-formed file called MyInputBad.xml. When we type "build" at the command line the following was the output:

 CheckXML:
 [xmlvalidate] C:\XMLClass\Ant\in\MyInputBad.xml:5:32: The element type "MyMessag
 e" must be terminated by the matching end-tag "</MyMessage>".

See also[edit]