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?
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.
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.
You can validate your XML documents against XML schemas only; validation against DTDs is not supported.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With