Skip to content

Instantly share code, notes, and snippets.

@mika76
Created July 11, 2022 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mika76/389d385acd2d9d04abe31356185d5104 to your computer and use it in GitHub Desktop.
Save mika76/389d385acd2d9d04abe31356185d5104 to your computer and use it in GitHub Desktop.
XSD Geneator in Powershell
# Adapted from https://mylifeismymessage.net/generate-xsd-schema-from-xml-using-powershell/
param (
[Parameter(Mandatory)] [string] $xmlFilename,
[string] $xsdSchemaFilename = $null
)
if ([string]::IsNullOrEmpty($xsdSchemaFilename)) {
$xsdSchemaFilename = $xmlFilename.Replace(".xml",".xsd")
}
Write-Host "XML Path: $xmlFilename" -ForegroundColor yellow
Write-Host "XSD Path: $xsdSchemaFilename" -ForegroundColor yellow
# Remove existing XSD
if (Test-Path -Path $xsdSchemaFilename) {
Remove-Item -Path $xsdSchemaFilename
}
$reader = [System.Xml.XmlReader]::create($xmlFilename)
$schemaSet = New-Object System.Xml.Schema.XmlSchemaSet
$schema = New-Object System.Xml.Schema.XmlSchemaInference
$schemaSet = $schema.InferSchema($reader)
# Create new output file
$file = New-Object System.IO.FileStream($xsdSchemaFilename, [System.IO.FileMode]::CreateNew)
$file.Close()
$xmlWriter = New-Object System.Xml.XmlTextWriter ($xsdSchemaFilename, [System.Text.Encoding]::UTF8)
$xmlWriter.Formatting = [System.Xml.Formatting]::Indented
foreach ($s in $schemaSet.Schemas())
{
$s.Write($xmlWriter)
}
$xmlWriter.Close()
Write-Host "See file: $xsdSchemaFilename"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment