Powershell: Generate simple XML from text, useful for CruiseControl.Net merge files

I had the problem that I need to include ordinary text files into the CruiseControl.Net build output log file. This log file is a merge of multiple files in xml format. So I needed to get some text files into a simple xml format. I ended up with the following Powershell code to convert an input text file to a simple output xml file

Powershell code:

function Convert-XmlString
    # Escape Xml markup characters (
    $text.replace('&', '&amp;').replace("'", '&apos;').replace('"', '&quot;').replace('<', '&lt;').replace('>', '&gt;')

function Convert-TextToXml
        $rootNode = 'root',
        $node = 'node',
        $path = $(Throw 'Missing argument: path'),
        $destination = $(Throw 'Missing argument: destination')
    Get-Content -Path $path | ForEach-Object `
        -Begin {
            Write-Output "<$rootNode>"
        } `
        -Process {
            Write-Output "  <$node>$(Convert-XmlString -text $_)</$node>"
        } `
        -End {
            Write-Output "</$rootNode>"
        } | Set-Content -Path $destination -Force

You can call this code as follows:

Convert-TextToXml -rootNode 'BuildAndPackageAll' -node 'message' -path 'c:\temp\in.txt' -destination 'c:\temp\out.xml'

where the file c:\temp\in.txt:

This is line 1
This is a line with the characters <, >, &, ' and "
This is line 3

Will be converted the the file c:\temp\out.xml:

  <message>This is line 1</message>
  <message>This is a line with the characters &lt;, &gt;, &amp;, &apos; and &quot;</message>
  <message>This is line 3</message>

No Comments