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
{
    param
    (
        [string]$text
    )
    # Escape Xml markup characters (
http://www.w3.org/TR/2006/REC-xml-20060816/#syntax)
    $text.replace('&', '&amp;').replace("'", '&apos;').replace('"', '&quot;').replace('<', '&lt;').replace('>', '&gt;')
}

function Convert-TextToXml
{
    param
    (
        $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:

<BuildAndPackageAll>
  <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>
</BuildAndPackageAll>

Published Monday, December 8, 2008 1:34 AM by svdoever
Filed under:

Comments

No Comments