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 $xmlWriter.WriteStartDocument() # Set the XSL $XSLPropText = "type='text/xsl' href='style.xsl'" $xmlWriter.WriteProcessingInstruction("xml-stylesheet", $XSLPropText) # Write Root Element $xmlWriter.WriteStartElement("RootElement") # Write the Document $xmlWriter.WriteStartElement("Servers") $xmlWriter.WriteElementString("Name","SERVER01") $xmlWriter.WriteElementString("IP","10.30.23.45") $xmlWriter.WriteEndElement # <-- Closing Servers # Write Close Tag for Root Element $xmlWriter.WriteEndElement # <-- Closing RootElement # End the XML Document $xmlWriter.WriteEndDocument() # Finish The Document $xmlWriter.Finalize $xmlWriter.Flush $xmlWriter.Close()