Generate a Schema from an XML File in PowerShell

While BizTalk includes an XML to XSD schema utility, we can do the same thing in C# or PowerShell (version 5.1 used in this example, but most of the work is done by .Net classes).

The .NET System.Xml libraries include something interesting called the XmlSchemaInference object.  It can basically look at the XML data file, and reverse engineer a schema from it.  It infers the schema, i.e. it does it’s best to create a schema that can be used to validate the data.

The tricky part is the loop. The sample below shows two ways to handle the loop. Inside the loop, we must pass the XmlWriter variable/object that we created to the Write method.

# from:
$xmlFilename = "c:\XMLClass\IntroSamples\Flight03.xml"
$xsdSchemaFilename = $xmlFilename.Replace(".xml","_dotNet_generated.xsd")

# Remove existing XSD - remove this if you don't want overlay existing file
# or maybe enhance to prompt the user if he wants to overwrite the file. 
if(Test-Path $xsdSchemaFilename)
      Remove-Item -Path $xsdSchemaFilename

#code converted from C# to PowerShell from here: 
#with enhancements and ideas from here: 

# I left in the C# code so you can see how it gets converted to PowerShell.</pre>
<pre>#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.