Created
July 11, 2022 08:57
-
-
Save mika76/389d385acd2d9d04abe31356185d5104 to your computer and use it in GitHub Desktop.
XSD Geneator in Powershell
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
# 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