Powershell saving XML and preserving format

You can use the PowerShell [xml] object and set $xml.PreserveWhitespace = $true, or do the same thing using .NET XmlDocument:

# NOTE: Full path to file is *highly* recommended
$f = Convert-Path '.\xml_test.xml'

# Using .NET XmlDocument
$xml = New-Object System.Xml.XmlDocument
$xml.PreserveWhitespace = $true

# Or using PS [xml] (older PowerShell versions may need to use psbase)
$xml = New-Object xml
$xml.PreserveWhitespace = $true
#$xml.psbase.PreserveWhitespace = $true  # Older PS versions

# Load with preserve setting
$xml.Load($f)
$n = $xml.SelectSingleNode('//file')
$n.InnerText="b"
$xml.Save($f)

Just make sure to set PreserveWhitespace before calling XmlDocument.Load or XmlDocument.LoadXml.

NOTE: This does not preserve white space between XML attributes! White space in XML attributes seem to be preserved, but not between. The documentation talks about preserving “white space nodes” (node.NodeType = System.Xml.XmlNodeType.Whitespace) and not attributes.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)