PowerShell v3 Function New XsdFromXml

This nothing more than a wrapper for my previous posts script: PowerShell (v3) - Inferring a Schema (XSD) from XML File. Nothing new if you read the last post.

function New-XsdFromXml
{
      <#
            .NOTES
                  .Author Will Steele (will.steele@live.com)
                  .Last Modified Date: 2012/08/11
                 
            .SYNOPSIS
                  Create XSD file from XML.
           
            .EXAMPLE
                  New-XsdFromXml -Xml C:data est.xml -Xsd C:data est.xsd
                 
            .PARAMETER Xml
                  A required string indicating a file path to an .xml file.
                 
            .PARAMETER Xsd
                  A required string indicating a file path to an output .xsd file.
                 
            .LINK
                  http://learningpcs.blogspot.com/2012/08/powershell-v3-function-new-xsdfromxml.html
      #>

      [CmdletBinding()]
      param(
            $Xml,
            $Xsd
      )

      # Read xml
      $reader = [System.Xml.XmlReader]::Create($Xml)

      # Instntiate XmlSchemaSet and XmlSchemaInference to process new XSD
      $schemaSet = New-Object System.Xml.Schema.XmlSchemaSet
      $schema = New-Object  System.Xml.Schema.XmlSchemaInference

      # Infer schemaSet from XML document in $reader
      $schemaSet = $schema.InferSchema($reader);

      # Create new output file
      $file = New-Object System.IO.FileStream($Xsd, [IO.FileMode]::CreateNew)

      # Create XmlTextWriter with UTF8 Encoding to write to file
      $xwriter = New-Object System.Xml.XmlTextWriter($file, [Text.Encoding]::UTF8)

      # Set formatting to indented
      $xwriter.Formatting = [System.Xml.Formatting]::Indented

      # Parse SchemaSet objects
      $schemaSet.Schemas() |
      ForEach-Object {
            [System.Xml.Schema.XmlSchema] $_.Write($xwriter)
      }

      # Close objects with handles on file
      $xwriter.Close()
      $reader.Close()
}

Related Posts by Categories

0 comments:

Post a Comment