Reading XML and Updating element - changing format of XML file, why?

Hi Everyone

The script below was created to read an xml file and then update the variable enableTest, in the xml file, from false to true; the variable is updated, however for some reason the format of the xml is changed, as any empty elements will have a carriage return created inside them - does anyone have any idea why?

$xml = [xml](Get-Content "C:\myfile.xml")

$xml.config.channels.channel | where { $_.id -ilike "ITEM_*" -and $_.id -inotlike "*_BAG"} | foreach {$_.enableTest = "true"}

$xml.Save("C:\myfile.xml - Copy.xml")

You are not showing the XML input or output so, that leaves us to guess at what you mean.

I changed my powershell script to what is shown below, this corrected the issue with the empty elements, but now I have an issue with two elements and everything inside these two elements is now being written along one line. apologies I cannot share the file.

$xml = [xml]([System.IO.File]::ReadAllText("C:\Users\esimms\Downloads\Micro\ChannelConfig.xml"))
$xml.PreserveWhitespace = $false

# Change some element
$xml.channelconfig.channels.channel | where { $_.id -ilike "NEXT_*" -and $_.id -inotlike "*_GB"} | foreach {$_.enableLazyLoadSearch = "true"}

#Settings object will instruct how the xml elements are written to the file
$settings = New-Object System.Xml.XmlWriterSettings
$settings.Indent = $true

#NewLineChars will affect all newlines
$settings.NewLineChars ="`r`n"

#Set an optional encoding, UTF-8 is the most used (without BOM)
$settings.Encoding = New-Object System.Text.UTF8Encoding( $true )

#write file and delete object
$w = [System.Xml.XmlWriter]::Create("C:\Users\esimms\Downloads\Micro\ChannelConfig Copiedv2.xml", $settings)
try{
$xml.Save( $w )
} finally{
$w.Dispose()
}

Better if you can format the code.

Instructions: https://powershell.org/forums/topic/read-me-before-posting-youll-be-glad-you-did/

OK, I’ve re-formatted the code…hope you or anyone else can give an explanation as to why the code would place all elements after a specific element all on one line.

There is no issue with PowerShell here, I’m not an expertise in XML objects too, I can try to get some XML experts to have a look.

But it’s very difficult to guess what type of elements are there in your XMLs at least for us to try. Can you create sample XMLs with same schema that you have and share here. Use git.github.com to post XML in this forum.

[XML]$XML = Get-Content "C:\Scripts\ps.org\config.xml"

$XML.ChannelConfig.Channels.Channel | ?{$PSItem.ID -ilike "NEXT_*" -and $PSItem.ID -inotlike "*_GB"} | % {$PSItem.enableLazyLoadSearch = 'True'}

$xml.Save("C:\Scripts\ps.org\config_copy.xml")

I tried to simulate and I am able to update a sample XML’s both Attribute and InnerText. For more details, please share the schema of your XML config file with dummy data.