Generate XSD Schema from XML using PowerShell

I found a C# example of how to create a schema from an XML file here.

I wanted to do the same in PowerShell, and this is what I came up with.
I left some of the C# code in the script below in comments, just for comparison purposes.

The program uses the .NET Schema Inference class.

<pre>
cls
#
# Specify your sample XML file, and it will use that file name to create a Schema name
# by replacing the .xml suffix to "dotNet.xsd"
#
$xmlFilename = "c:\XMLClass\IntroSamples\Flight01_Complex.xml"
$xsdSchemaFilename = $xmlFilename.Replace(".xml","_dotNet.xsd")

# Remove existing XSD

if(Test-Path $xsdSchemaFilename)
{
      Remove-Item -Path $xsdSchemaFilename
}

#code converted from C# to PowerShell from here: 
#https://stackoverflow.com/questions/22835730/create-xsd-from-xml-in-code/22836075
#with enhancements from here: 
#https://learningpcs.blogspot.com/2012/08/powershell-v3-inferring-schema-xsd-from.html

#XmlReader reader = XmlReader.Create("contosoBooks.xml");
$reader = [System.Xml.XmlReader]::create($xmlFilename)
#XmlSchemaSet schemaSet = new XmlSchemaSet()
#XmlSchemaInference schema = new XmlSchemaInference()
#https://docs.microsoft.com/en-us/dotnet/api/system.xml.schema.xmlschemaset?view=netcore-3.1
$schemaSet = New-Object System.Xml.Schema.XmlSchemaSet
#https://docs.microsoft.com/en-us/dotnet/api/system.xml.schema.xmlschemainference?view=netcore-3.1
$schema = New-Object System.Xml.Schema.XmlSchemaInference 

#schemaSet = schema.InferSchema(reader);
$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

$loopCounter = 0 
foreach ($s in $schemaSet.Schemas())
{
   $loopCounter++
   Write-Host "LoopCounter: $loopCounter"
   $s.Write($xmlWriter) 
   
}

$xmlWriter.Close()
Write-Host "See file: $xsdSchemaFilename"
</pre>

Uncategorized  

Leave a Reply