Tuesday, June 23, 2015

PowerShell : XML schema validation



I have this script to validate an XML file against a schema. The module exposes a Test-XmlSchema function that accepts an XML file and a Schema file as parameters and validates the XML file against the schema.

function Test-XmlSchema
{
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateScript({Test-Path $_})]
        [String]
        $XmlPath,
       
        [Parameter(Mandatory = $true)]
        [ValidateScript({Test-Path $_})]
        [String]
        $SchemaPath
    )

    $schemas = New-Object System.Xml.Schema.XmlSchemaSet
       $schemas.CompilationSettings.EnableUpaCheck = $false
       $schema = ReadSchema $SchemaPath
       [void]($schemas.Add($schema))
       $schemas.Compile()
      
       try
    {
        [xml]$xmlData = Get-Content $XmlPath
              $xmlData.Schemas = $schemas

        #Validate the schema. This will fail if is invalid schema
              $xmlData.Validate($null)
              return $true
       }
    catch [System.Xml.Schema.XmlSchemaValidationException]
    {
              return $false
       }
}

Function ReadSchema
{
       param($SchemaPath)
       try
    {
              $schemaItem = Get-Item $SchemaPath
              $stream = $schemaItem.OpenRead()
              $schema = [Xml.Schema.XmlSchema]::Read($stream, $null)
              return $schema
       }
       catch
    {
              throw
       }
       finally
    {
              if($stream)
        {
                     $stream.Close()
              }
       }
}

Export-ModuleMember -Function Test-XmlSchema


Usage:

PS C:\> Import-Module XML

PS C:\> Test-XMLSchema -XmlPath E:\Test.xml -SchemaPath E:\Test.xsd
True




No comments: