If you don't need to use a specific xml schema, you can import a csv, and export to xml all in one go using ConvertTo-Xml:
Username, Password, Email
mike, iamcool, [email protected]
john, hunter2, [email protected]
# First, we import from a csv, then we can directly export to xml:
$csv = Import-CSV -Path 'c:\path\to\file.csv'
ConvertTo-XML $csv -as String -NoTypeInformation
# Or as one line, exporting to file:
Import-CSV $path | ConvertTo-Xml -as String -NoTypeInformation | Out-File $xmlpath
<?xml version="1.0" encoding="utf-8"?>
<Objects>
<Object>
<Property>
<Property Name="Username">mike</Property>
<Property Name="Password">iamcool</Property>
<Property Name="Email">[email protected]</Property>
</Property>
<Property>
<Property Name="Username">john</Property>
<Property Name="Password">hunter2</Property>
<Property Name="Email">[email protected]</Property>
</Property>
</Object>
</Objects>
If you do need to match an existing schema, I would do it the .Net way. For example, to try and match your sample schema:
$csv = Import-Csv 'c:\path\to\file.csv'
# Create an XML object, and give it a declaration line
$xml = [System.Xml.XmlDocument]::new()
$dec = ($xml.CreateXmlDeclaration("1.0", "UTF-8", $null))
$root = $xml.DocumentElement
$xml.InsertBefore($dec,$root)
# create main <body> node
$xmlbody = $xml.CreateElement('Body')
$xml.AppendChild($xmlbody)
# import csv to custom nodes
foreach ($user in $csv) {
# create <user> container node
$xmluser = $xml.CreateElement('User')
$xmlbody.AppendChild($xmluser)
# add each property from csv entry to <user>
Foreach ($property in $csv[0].psobject.Properties.name) {
# create a property node
$xmlproperty = $xml.CreateElement($property)
$text = $xml.CreateTextNode($user.$property)
$xmlproperty.AppendChild($text)
# add to current <User> node
$xmluser.AppendChild($xmlproperty)
}
}
# output text
$xml|Format-Xml
# or save to file
$xml.Save('c:\path\to\file.xml')
<?xml version="1.0" encoding="UTF-8"?>
<Body>
<User>
<Username>mike</Username>
<Password>iamcool</Password>
<Email>[email protected]</Email>
</User>
<User>
<Username>john</Username>
<Password>hunter2</Password>
<Email>[email protected]</Email>
</User>
</Body>
Both methods handle encoding special characters for you.