Designing XML Documents

by Mar 22, 2016

Today we start a little mini series about XML. To create sample data to play with, you will first create a well-formed XML. While you can create XML documents with text operations manually, this leaves room for mistakes. A better way is to use the specialized XmlTextWriter object. It can write all the opening and closing tags to an XML file that you may need.

# this is where the document will be saved
$Path = "$env:temp\inventory.xml"
# get an XmlTextWriter to create the XML
$XmlWriter = New-Object System.XMl.XmlTextWriter($Path,$Null)
# choose a pretty formatting
$xmlWriter.Formatting = 'Indented'
$xmlWriter.Indentation = 1
$XmlWriter.IndentChar = "`t"
# write the header
# set XSL statements
$xmlWriter.WriteProcessingInstruction("xml-stylesheet", "type='text/xsl' href='style.xsl'")
# create root element "machines" and add some attributes to it
$XmlWriter.WriteComment('List of machines')
$XmlWriter.WriteAttributeString('current', $true)
$XmlWriter.WriteAttributeString('manager', 'Tobias')
# add a couple of random entries
for ($x=1 $x -le 10 $x++)
    $server = 'Server{0:0000}' -f $x
    $ip = '{0}.{1}.{2}.{3}' -f  (0..256 | Get-Random -Count 4)
    $guid = [System.GUID]::NewGuid().ToString()
    # each data set is called "machine", add a random attribute to it
    $XmlWriter.WriteComment("$x. machine details")
    $XmlWriter.WriteAttributeString('test', (Get-Random))
    # add three pieces of information
    # add a node with attributes and content
    $XmlWriter.WriteAttributeString('info1', 'some info')
    $XmlWriter.WriteAttributeString('info2', 'more info')
    # add a node with CDATA section
    $XmlWriter.WriteAttributeString('info3', 'another attribute')
    $XmlWriter.WriteCData('this is untouched code and can contain special characters /\@<>')
    # close the "machine" node
# close the "machines" node
# finalize the document
notepad $path

The result is perfect XML and can be opened in a text editor.

Twitter This Tip! ReTweet this Tip!