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?
The problems were all related:
Get-Contentreturns 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: