Powershell: Write XML files with UNIX line endings

Hi,

if you want to create XML files with powershell which can be used on UNIX/Linux systems you need to write an own save function. Ths save() methode of the System.XML.XMLDocument class can only write Windows style XML files with Carriage return/New line endings.

This is a function which write Linux/UNIX style UTF8 files

function Write-UnixXml {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true, Position=0)][xml]$xmlStructure,
        [Parameter(Mandatory=$true, Position=1)][string]$FullPath
    )
    $oXMLWriterSettings = new-object System.Xml.XmlWriterSettings
    $oXMLWriterSettings.NewLineChars = "`n"                                      
    $oXMLWriterSettings.Indent       = $true                                     
    $oXMLWriterSettings.IndentChars  = "`t"
    $oXMLWriterSettings.NewLineHandling = 0
    $oXMLWriterSettings.Encoding     = new-object System.Text.UTF8Encoding  
    try
    {
        $oXMLWriter = [System.Xml.XmlTextWriter]::Create($FullPath, $oXMLWriterSettings)
        $xmlStructure.WriteTo($oXMLWriter)
        $oXMLWriter.Flush()
        $oXMLWriter.Close()
    }
	catch
	{
		write-host ([string]::Format(" Error occured while writing XML file {0}. Errormessage: {1})",$FullPath,$_.Exception.Message))
	}
}

Usage

PS D:\> [[xml]] $TestXML='<config>MyConfig <Value number="1"></Value></config>'
PS D:\> Write-UnixXml -xmlStructure $TestXML -FullPath D:\temp\text.xml

Michael

Leave a Reply