Kushal Solanki
Kushal Solanki

Reputation: 127

Modifying xml with System.Xml.XmlDocument PreserveWhitespace property is adding extra space before end tag

I am modifying below xml with System.Xml.XmlDocument and setting PreserveWhitespace property to true before load but when I save it, its adding an extra space before end tag.

XML: `

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings file="twCustomerSettings.config">
        <add key="HubUserName" value="" />
        <add key="HubPassword" value="" />
        <add key="IgnoreHubCertErrors" value="false" />
        <add key="NounVerbMetaSetsDirectory" value="C:\Program Files (x86)\AHS\NounVerbMetaData\"/>
        <add key="HOSTNAME_WHITELIST" value="127.0.0.1,::1:,::1" />
        <add key="impersonate" value="false" />
        <add key="securityMode" value="Transport" />
        <add key="QueryBuilder" value="enabled" />
        <add key="iHealthProxyClinicalDocument.ClinicalDocument" value="http://localhost/iHealthProxy/ClinicalDocument.asmx" />
    </appSettings>
</configuration>

`

Script:

$WhitelistServersIPs = "10.131.42.202,10.25.1.25,10.135.0.33"
$ISAPIWebConfigFilePath = "C:\web.config"

$ISAPIConfig = New-Object System.Xml.XmlDocument
$ISAPIConfig.PreserveWhitespace = $true
$ISAPIConfig.Load($ISAPIWebConfigFilePath)
$HOSTNAME_WHITELIST = $ISAPIConfig | Select-XML –Xpath "//*[@key='HOSTNAME_WHITELIST']"

Write-Host "Updating HOSTNAME_WHITELIST....."
$HOSTNAME_WHITELIST.Node.Value = $WhitelistServersIPs
$ISAPIConfig.Save($ISAPIWebConfigFilePath)
Write-Host "File updated and saved....."

Please note that NounVerbMetaSetsDirectory key do not have space before /> closing tag, while all other nodes have it. After saving the file an extra space is added and line becomes below. I want to preserver exact formatting as it was before. <add key="NounVerbMetaSetsDirectory" value="C:\Program Files (x86)\AHS\NounVerbMetaData\" />

Upvotes: 0

Views: 207

Answers (1)

vonPryz
vonPryz

Reputation: 24081

To prevent extra whitespace is, unfortunately, going to require a lot of effort. XMLDoucment.Save() calls .Net internal methods and seems to end up in XmlTextWriter.cs. Over there, it's got a hard coded space before slash:

    void WriteEndStartTag(bool empty) {
        ...
        xmlEncoder.EndAttribute();
        if (empty) {
            textWriter.Write(" /"); // space-slash
        }
        textWriter.Write('>');
    }

If you really need to get rid of that space, roll your own XML serializer, or edit the file as text instead of XML. The latter alternative ignores XML validation, so be extra careful not to wreck the config file.

Upvotes: 1

Related Questions