If you want to save the xml as UTF-8 without BOM and have unix style newline characters \n
instead of \r\n
, you cannot use the standard Save()
method on Windows and need to create a function yourself to do that.
Using your previous question as example, you could do this:
[xml]$xmldata = @"
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Identity PUBLIC "point.dtd" "point.dtd"[]>
<Identity created="1525465321820" name="Onboarding - GUI - External">
<Attributes>
<Map>
<entry key="displayName" value="Onboarding - GUI " />
<entry key="firstname" value="Z Orphaned ID" />
</Map>
</Attributes>
</Identity>
"@
# do something with the xml data
To save the xml to file with UNIX style newlines and also in UTF-8 No BOM encoding, you can use this function:
function Out-UnixXml {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline = $true, Mandatory = $true, Position = 0)]
[xml]$xml,
[Parameter(ValueFromPipeline = $true, Mandatory = $true, Position = 1)]
[Alias('FilePath')]
[string]$Path
)
try {
$settings = [System.Xml.XmlWriterSettings]::new()
$settings.Indent = $true # defaults to $false
$settings.NewLineChars = "`n" # defaults to "`r`n"
$settings.Encoding = [System.Text.UTF8Encoding]::new($false) # $false means No BOM
$xmlWriter = [System.Xml.XmlWriter]::Create($Path, $settings)
$xml.WriteTo($xmlWriter)
$xmlWriter.Flush()
}
finally {
# cleanup
if ($xmlWriter) { $xmlWriter.Dispose() }
}
}
And use it like this instead of $xmldata.Save('C:\somefile.xml')
Out-UnixXml $xmldata 'C:\somefile.xml'
As for the square brackets in the DOCTYPE declaration. see XmlDocument.Save() inserts empty square brackets in doctype declaration