How do I use PowerShell to Validate XML files against an XSD?

前端 未结 8 1896
小鲜肉
小鲜肉 2020-12-05 02:26

As a part of my development I\'d like to be able to validate an entire folder\'s worth of XML files against a single XSD file. A PowerShell function seems like a good candid

8条回答
  •  失恋的感觉
    2020-12-05 03:12

    I want to comment that the script in current accepted answer doesn't validate errors about incorrect orders of elements of xs:sequence. For example: test.xml

    
      
    Baker street 5 Joe Tester

    test.xsd

        
    
          
           
             
           
         
        
    
         
          
           
             
             
           
          
         
    
         
         
        
    

    I wrote another version that can report this error:

    function Test-XmlFile
    {
        <#
        .Synopsis
            Validates an xml file against an xml schema file.
        .Example
            PS> dir *.xml | Test-XmlFile schema.xsd
        #>
        [CmdletBinding()]
        param (     
            [Parameter(Mandatory=$true)]
            [string] $SchemaFile,
    
            [Parameter(ValueFromPipeline=$true, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
            [alias('Fullname')]
            [string] $XmlFile,
    
            [scriptblock] $ValidationEventHandler = { Write-Error $args[1].Exception }
        )
    
        begin {
            $schemaReader = New-Object System.Xml.XmlTextReader $SchemaFile
            $schema = [System.Xml.Schema.XmlSchema]::Read($schemaReader, $ValidationEventHandler)
        }
    
        process {
            $ret = $true
            try {
                $xml = New-Object System.Xml.XmlDocument
                $xml.Schemas.Add($schema) | Out-Null
                $xml.Load($XmlFile)
                $xml.Validate({
                        throw ([PsCustomObject] @{
                            SchemaFile = $SchemaFile
                            XmlFile = $XmlFile
                            Exception = $args[1].Exception
                        })
                    })
            } catch {
                Write-Error $_
                $ret = $false
            }
            $ret
        }
    
        end {
            $schemaReader.Close()
        }
    }
    

    PS C:\temp\lab-xml-validation> dir test.xml | Test-XmlFile test.xsd

    System.Xml.Schema.XmlSchemaValidationException: The element 'address' has invalid child element 'name'.
    ...
    

提交回复
热议问题