Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify xml while preserving whitespace

Tags:

powershell

I'm running into several problems trying to replace an attribute in an XML file while preserving whitespace.

Attempt 1

$xml = [xml](get-content data.xml)
$xml.Path.To.Attribute = $value
set-content data.xml [String]$value

Result: Insigificant whitespace (namely newlines) are removed

Attempt 2

$xml = new-object xml
$xml.PreserveWhitespace = true
$xml.PreserveWhitespace

Result: PreserveWhitespace remains false

Attempt 3

$xml = get-content data.xml
$xml = [regex]::replace($xml, "pattern", "replacement")
set-content data.xml $xml

Result: [regex]::replace messes up the line endings

Am I taking crazy pills here?

like image 756
Richard Szalay Avatar asked Dec 09 '22 08:12

Richard Szalay


1 Answers

The problems were all related: Get-Content returns lines of the text file, not the text itself. When cast back to a string, the lines are combined outright.

The best solution was to use:

$xml = [xml]([System.IO.File]::ReadAllText("data.xml"))
like image 124
Richard Szalay Avatar answered Dec 18 '22 15:12

Richard Szalay