Reputation: 57
I'm using the following PowerShell to update the value of an element in some XML which works fine, but when I save the XML it appears to change the formatting.
$xmlFileName = "D:\scripts\DbRestoreDIFF.xml"
[xml]$xmlDoc = Get-Content $xmlFileName
$xmlDoc.TMMsg_CreateTaskReq.taskInfo.subTasks.options.restoreOptions.browseOption.timeRange.toTimeValue = $Timestamp
$xmlDoc.Save($xmlFileName)
After I save the document there are several elements where the format goes from:
<alert>
<alertName></alertName>
</alert>
to:
<alert>
<alertName>
</alertName>
</alert>
I've tried preserving whitespace but it didn't seem to help. This is causing me an issue as I'm them unable to pass the XML correctly.
Upvotes: 0
Views: 51
Reputation: 24071
The default values in XmlDocument's save()
are cause for this issue. As described, start and end tags are on different lines:
[xml]$x = '<alert> <alertName></alertName> </alert>'
$x.save([console]::out)
# Output
<?xml version="1.0" encoding="ibm850"?>
<alert>
<alertName>
</alertName>
</alert>
To control the output formatting, use an XmlWriter with XmlWriterSettings. An example that saves output to console is like so,
[xml]$x = '<alert> <alertName></alertName> </alert>'
$settings = $(new-object Xml.XmlWriterSettings)
$settings.Indent = $true
$settings.IndentChars = "`t"
$xmlWriter = [Xml.XmlWriter]::create([console]::out, $settings)
$x.save($xmlWriter)
$xmlWriter.close()
# Output
<?xml version="1.0" encoding="ibm850"?>
<alert>
<alertName></alertName>
</alert>
Upvotes: 1