We all know I have OCD when it comes to formatting. Using the built in PowerShell cmdlets (Export-XmlCli) to export XML left me with a mess of an XML Schema that I couldn’t apply a XSL Transform to. I needed something that would allow me to control the schema, and insert the XSL declaration. After doing quite a bit of online searching and research, I decided to try using the .NET class System.XML.XmlTextWriter. The code sample below is the basic snippet using the class and creating a document.

A couple of notes:

  • $filepath will need to be set to the full file path, using “.\” will not work.
  • If you are creating a complex file, you will want to note which tag you are closing with the WriteEndElement.
# Set the File Name
$filePath = "C:\Reports\Report.xml"

# Create The Document
$XmlWriter = New-Object System.XMl.XmlTextWriter($filePath,$Null)

# Set The Formatting
$xmlWriter.Formatting = "Indented"
$xmlWriter.Indentation = "4"

# Write the XML Decleration

# Set the XSL
$XSLPropText = "type='text/xsl' href='style.xsl'"
$xmlWriter.WriteProcessingInstruction("xml-stylesheet", $XSLPropText)

# Write Root Element

# Write the Document
$xmlWriter.WriteEndElement # <-- Closing Servers

# Write Close Tag for Root Element
$xmlWriter.WriteEndElement # <-- Closing RootElement

# End the XML Document

# Finish The Document