1
votes

So I'm trying to learn how to modify XML files with PowerShell but am encountering a weird issue, where PowerShell adds blank space to my XML files after saving them.

Say I have an xml file called test.xml that looks like:

<employee>
    <person>
        <name>John Doe</name>
        <id></id>
    </person>
</employee>

I wrote this PowerShell script to change the name:

$file1 = ".\test.xml"
$file2 = ".\test_new.xml"
$xml = New-Object XML
$xml.Load($file1)
$xml.employee.person.name = "John Smith"
$xml.Save($file2)

So far, so good. However, the output file is formatted like this:

<employee>
    <person>
        <name>John Smith</name>
        <id>
       </id>
    </person>
</employee>

This is a problem, because I am trying to use similar code to update an XML file with a schema that restricts including spaces in blank fields. This makes it unreadable after modification. Anyone know what I'm doing wrong here?

2

2 Answers

2
votes

This appears to work for me:

$file1 = ".\test.xml"
$file2 = ".\test_new.xml"

# Remove old variable to ensure new instance
Remove-Variable xml -ea SilentlyContinue

# Create new empty xmldoc
$xml = New-Object XML

# Set preserve whitespace before load
$xml.PreserveWhiteSpace = $true
$xml.Load($file1)

$xml.employee.person.name = "John Smith"

#Set it again before save
$xml.PreserveWhiteSpace = $true
$xml.Save($file2)
0
votes

Another option is to use a command from the PowerShell Community Extensions called Format-Xml e.g.:

...
$xml.employee.person.name = "John Smith"
$xml | Format-Xml > $file2