Validate XML Syntax in the Command Line

This example shows how to parse and validate XML in the terminal using the command xmllint.
Note that this is testing if the document is well formed, i.e. has correct syntax, not validity according to a specific schema.

Input file: items.xml

<items>
  <item>
    <name>A</name>
  </item>
  <item>
    <name>B</name>
  </item>
</items>

Test the file:

$ xmllint items.xml

For a valid file, the output will be a copy of the entire file, without error messages:

<?xml version="1.0"?>
<items>
  <item>
    <name>A</name>
  </item>
  <item>
    <name>B</name>
  </item>
</items>

If there is a syntax error, as below, the line number will be reported.

Input file with error: items.xml

<items>
  <item>
    <name>A<name> <!-- improper close tag -->
  </item>
  <item>
    <name>B</name>
  </item>
</items>

The error output will look like this:

items.xml:4: parser error : 
Opening and ending tag mismatch: name line 3 and item
</item>
^
items.xml:8: parser error : 
Opening and ending tag mismatch: name line 3 and items
</items>
^
items.xml:11: parser error : 
Premature end of data in tag item line 2

^

 

Leave a Reply

Your email address will not be published. Required fields are marked *