Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify whether a xml file is valid in sh or bash?

Tags:

bash

sh

xml

xmllint

How to verify whether a XML file is valid in sh (preferably) or bash?

I have a file that often get corrupted and needs to be replaced while I take my time to investigate the underlying issue.

Is there any easy way of performing this task with sh or bash?

like image 482
user2799603 Avatar asked Feb 28 '14 15:02

user2799603


People also ask

Which tool is used to check whether XML document is valid or not?

Tools. xmllint is a command line XML tool that can perform XML validation. It can be found in UNIX / Linux environments. XML Validator Online Validate your XML data.

How do I view XML files in Linux?

xml file you want to view. If you're using Gnome, you can open GNOME Files and double-click the folder where the file is stored. If you're using KDE, the built-in file manager is Dolphin. Right-click the file and select Open With Other Application.

Can we validate XML schema?

You can validate your XML documents against XML schemas only; validation against DTDs is not supported.


2 Answers

Not directly with bash, but xmllint is fairly widely available.

xmllint --format "${xmlfile}"

This will exit with non-zero status (hint: $? in bash gets you the exit code of the last command) if the XML file is invalid.

like image 164
sanmiguel Avatar answered Sep 27 '22 19:09

sanmiguel


XMLStarlet has a validate subcommand. At its simplest, to check for well-formedness:

xmlstarlet val "$filename"

To validate against a DTD:

xmlstarlet val -d "$dtd_filename" "$xml_filename"

To validate against an XSD schema:

xmlstarlet val -s "$xsd_filename" "$xml_filename"

To validate against a RelaxNG schema:

xmlstarlet val -r "$rng_filename" "$xml_filename"

This isn't built into bash -- bash has no built-in XML parser, and validation cannot be performed without one -- but it is widely packaged for modern OS distributions.


XMLStarlet also has subcommands for extracting information from XML files, editing XML files, etc. If you're going to be working with XML from shell scripts, its use is well-advised.

like image 23
Charles Duffy Avatar answered Sep 27 '22 21:09

Charles Duffy