From ac04c834998919f8170ed2d9a76c91d90cf46863 Mon Sep 17 00:00:00 2001 From: Markus Fleschutz Date: Wed, 30 Sep 2020 15:25:52 +0200 Subject: [PATCH] Added validate_xml.ps1 --- README.md | 1 + Scripts/validate_xml.ps1 | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 Scripts/validate_xml.ps1 diff --git a/README.md b/README.md index 52a506de..c164fc0a 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ PowerShell Scripts Included * [train_dns_cache.ps1](Scripts/train_dns_cache.ps1) - trains the DNS cache with frequently used domain names * [translate.ps1](Scripts/translate.ps1) - translates the given text * [txt2wav.ps1](Scripts/txt2wav.ps1) - converts text into a audio .WAV file +* [validate_xml.ps1](Scripts/validate_xml.ps1) - validates the given XML file * [weather.ps1](Scripts/weather.ps1) - prints the current weather forecast * [wakeup.ps1](Scripts/wakeup.ps1) - sends a magic packet to the given computer, waking him up * [zipdir.ps1](Scripts/zipdir.ps1) - creates a zip archive of the given folder diff --git a/Scripts/validate_xml.ps1 b/Scripts/validate_xml.ps1 new file mode 100644 index 00000000..e085f53a --- /dev/null +++ b/Scripts/validate_xml.ps1 @@ -0,0 +1,30 @@ +function Validate-Xml { + param ([string]$XmlFilePath) + try { + # Get the file + $XmlFile = Get-Item($XmlFilePath) + + # 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({ $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 + $false + } else { + # XML is valid + $true + } + } catch { + Write-Warning "$($MyInvocation.MyCommand.Name) - Error: $($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)" + } +}