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.

# 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: 
#with enhancements from here: 

#XmlReader reader = XmlReader.Create("contosoBooks.xml");
$reader = [System.Xml.XmlReader]::create($xmlFilename)
#XmlSchemaSet schemaSet = new XmlSchemaSet()
#XmlSchemaInference schema = new XmlSchemaInference()
$schemaSet = New-Object System.Xml.Schema.XmlSchemaSet
$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)

$xmlWriter = New-Object System.Xml.XmlTextWriter ($xsdSchemaFilename, [System.Text.Encoding]::UTF8)
$xmlWriter.Formatting = [System.Xml.Formatting]::Indented

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

Write-Host "See file: $xsdSchemaFilename"

Leave a Reply

Recent Posts




All Rights Reserved Theme by 404 THEME.