I want to read in an XML file and modify an element then save it back to the file. What is the best way to do this while preserving the format and also keep matching Line terminator (CRLF vs LF)?
Here is what I have but it doesn’t do that:
$xml = [xml]([System.IO.File]::ReadAllText($fileName))
$xml.PreserveWhitespace = $true
# Change some element
$xml.Save($fileName)
The problem is that extra new lines (aka empty lines in the xml) are removed and after I have mixed LF and CRLF.
You can use the PowerShell [xml] object and set
$xml.PreserveWhitespace = $true, or do the same thing using .NETXmlDocument:Just make sure to set PreserveWhitespace before calling
XmlDocument.LoadorXmlDocument.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.