#PSCXTip Testing XML for well-formedness and validity against a schema

We often deal with XML files whether it is modifying TFS work item templates, C# project files, or our own XML data files. When making quick changes to an XML file in a simple editor like Notepad, it is prudent to check the updated XML file before checking it back in or deploying it. The PowerShell Community Extensions (1.2 and higher) provides a command to do just that called Test-Xml. Using Test-Xml is quite simple:

PS> '<doc><book/><book></doc>' | Test-Xml

WARNING: The 'book' start tag on line 1 position 14 does not match the end tag of 'doc'. Line 1, position 21.

Having a well-formed XML file is a good thing but that doesn’t necessarily mean the schema of the XML file is correct. If there is a schema (.xsd) file for your XML, you can use it to do further validation. For instance, given this degenerate web.config file:

<?xml version="1.0" encoding="utf-8"?>

The above file is well formed e.g.:

PS> Test-Xml .\web.config

However that doesn’t mean everything is right with this file. Upon validating using a schema file provided by Visual Studio we can see that there is a problem:

PS> Test-Xml .\web.config -Validate -SchemaPath 'C:\Program Files (x86)\Microsoft Visual Studio 11.0\Xml\Schemas\1033\DotNetConfig.xsd' –Verbose
VERBOSE: Error: The 'Configuration' element is not declared. Line 2, Position 2.

As it turns out, XML element names are case-sensitive and the configuration element should have been specified like so:

<?xml version="1.0" encoding="utf-8"?>

With that slight change, we have both a well-formed and schema validated XML file e.g.:

PS> Test-Xml .\web.config -Validate -SchemaPath 'C:\Program Files (x86)\Microsoft Visual Studio 11.0\Xml\Schemas\1033\DotNetConfig.xsd'

Note: There are many more useful PowerShell Community Extensions (PSCX) commands. If you are interested in this great community project led by PowerShell MVPs Keith Hill and Oisin Grehan, give PSCX a try at http://pscx.codeplex.com.

Filed in: Columns, Tips and Tricks Tags: , ,
© 6642 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: