Created
April 1, 2019 07:35
-
-
Save rikwatson/f35c6016b6fcb9a43525e4872077593e to your computer and use it in GitHub Desktop.
Validates an XML file against its inline provided schema reference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Validate Schema | |
# | |
# Description | |
# ----------- | |
# Validates an XML file against its inline provided schema reference | |
# | |
# Command line arguments | |
# ---------------------- | |
# xmlFileName: Filename of the XML file to validate | |
param([string]$xmlFileName) | |
# Check if the provided file exists | |
if((Test-Path -Path $xmlFileName) -eq $false) | |
{ | |
Write-Host "XML validation not possible since no XML file found at '$xmlFileName'" | |
exit 2 | |
} | |
# Get the file | |
$XmlFile = Get-Item($xmlFileName) | |
# Keep count of how many errors there are in the XML file | |
$script:errorCount = 0 | |
# Perform the XSD Validation | |
$readerSettings = New-Object -TypeName System.Xml.XmlReaderSettings | |
$readerSettings.ValidationType = [System.Xml.ValidationType]::Schema | |
$readerSettings.ValidationFlags = [System.Xml.Schema.XmlSchemaValidationFlags]::ProcessInlineSchema -bor [System.Xml.Schema.XmlSchemaValidationFlags]::ProcessSchemaLocation | |
$readerSettings.add_ValidationEventHandler( | |
{ | |
# Triggered each time an error is found in the XML file | |
Write-Host $("`nError found in XML: " + $_.Message + "`n") -ForegroundColor Red | |
$script:errorCount++ | |
}); | |
$reader = [System.Xml.XmlReader]::Create($XmlFile.FullName, $readerSettings) | |
while ($reader.Read()) { } | |
$reader.Close() | |
# Verify the results of the XSD validation | |
if($script:errorCount -gt 0) | |
{ | |
# XML is NOT valid | |
exit 1 | |
} | |
else | |
{ | |
# XML is valid | |
exit 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment