Recently, I came up with a requirement of creating an XML file as output using PowerShell code. I want to get some service information from each computer and save the results to an XML file. Post this, the XML file will be consumed by an external trend reporting process. In this article, I am going to explain with simple XML creation method using XmlWrite with some static inputs.

STEP #1: Create & Set The Formatting with XmlWriterSettings class

First, we need to get an XmlTextWriter object to create the XML and assign the Indent values as true to make the elements to be arranged in a new line. The XmlWriterSettings class provides properties that control data conformance and output format.

$xmlObjectsettings = New-Object System.Xml.XmlWriterSettings
#Indent: Gets or sets a value indicating whether to indent elements.
$xmlObjectsettings.Indent = $true
$xmlObjectsettings.IndentChars = ” “

STEP #2: Set the XML File Path and Create The Document

# Set the File path & Create The Document
$XmlFilePath = “C:\dotnet-helpers\MyXmlFile.xml”
$XmlObjectWriter = [System.XML.XmlWriter]::Create($XmlFilePath, $xmlObjectsettings)

STEP #3 : Write the XML Declaration

When WriteStartDocument is called the writer validates that what you are writing is a well-formed XML document.For example, it checks that the XML declaration is the first node, that one and only one root-level element exists, and so on. If this method is not called, the writer assumes an XML fragment is being written and applies no root level rules.

#Write the XML delcaration.
$XmlObjectWriter.WriteStartDocument()

STEP #4: Start the Root Element and build with child nodes

In this step we are going to form the HTML elments using the WriteStartElement , WriteEndElement() ,WriteElementString , WriteComment…

XmlObjectWriter.WriteComment(“writes out a start tag with the specified local name.”)
$XmlObjectWriter.WriteStartElement(“BaseSettings“) # <– BaseSettings

$XmlObjectWriter.WriteStartElement(“ConfigSettings“) # <– Start ConfigSettings
$XmlObjectWriter.WriteElementString(“India”,”200$”)
$XmlObjectWriter.WriteElementString(“UAE”,”150$”)

$XmlObjectWriter.WriteStartElement(“ChildConfigSettings“) # <– Start ChildConfigSettings
$XmlObjectWriter.WriteElementString(“UK”,”250$”)

$XmlObjectWriter.WriteEndElement() # <– End ChildConfigSettings
$XmlObjectWriter.WriteEndElement() # <– End ConfigSettings
$XmlObjectWriter.WriteEndElement() # <– End BaseSettings

STEP #5 : Finally close the XML Document

$XmlObjectWriter.WriteEndDocument()
$XmlObjectWriter.Flush()
$XmlObjectWriter.Close()

Full Code

Output XML File :

There are additional ways to create custom XML. and there are plenty of methods that we can experiment. We will discuss in the upcoming posts