Change xml keeping spaces

I am having trouble replacing an attribute in an XML file while saving spaces.

Attempt 1

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

Result: Exceptional spaces (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 puts the end of the line

Am I taking crazy pills with me?

+4
powershell
source share
2 answers

All problems are related: Get-Content returns the lines of the text file, not the text itself. When you return to a line, the lines are combined in the forward direction.

The best solution was to use:

 $xml = [xml]([System.IO.File]::ReadAllText("data.xml")) 
+8
source share

This does not work because PreserveWhiteSpace is logical:

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

Using:

  xml.PreserveWhitespace = $true 
+6
source share

All Articles