0

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.

2
  • What do you mean with _pass the XML correctly_ ? What issues are cause by this? Commented May 25, 2020 at 8:07
  • It isn't read correctly by the application that reads it, which in this instance is Commvault. It assumes there is a value supplied when it is actually blank. Commented May 25, 2020 at 8:10

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the help. A variation of the above enabled me to update the XML as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.