Home > Mobile >  Need help to preserve XML hard return in a tag
Need help to preserve XML hard return in a tag

Time:03-08

I'm currently trying to download XML file using Powershell, there are some nodes in the file have format like below:

<BackendSystemSettings>
    <Backend
    a ="123" 
    b="ABC" 
    c="ABC123"/>
    <Backend
    a ="456" 
    b="DEF" 
    c="DEF456"/>
</BackendSystemSettings>

I want to keep that format, but when I save the xml file, all the elements in this tag are put into 1 line:

<BackendSystemSettings>
    <Backend a ="123" b="ABC" c="ABC123"/>
    <Backend a ="456" b="DEF" c="DEF456"/>
</BackendSystemSettings>

Above is just an example, in my real data, it's much longer, so when all the lines are merged into 1 lines, it will be very hard to check later on since the line is too long.

I tried to use Select-XML, PreserveWhitespace but nothing works. Do you guys have any suggestion?

Thank you very much!

CodePudding user response:

You can define more complex rules on how the XML should be saved through the XmlWriterSettings class.

It is important to note that the input format is not preserved. Rather, the output is formatted according to the rules presented by that class.

In your case, the rules I used are :

  • Indent: Whether to indent elements
  • NewLineOnAttributes : Whether to write attributes on individual lines (has no effect when Indent is false).
  • OmitXmlDeclaration: Whether to write an XML declaration.

Check the official documentation here to view all the rules available and what they do.


Now, what you want to see:

Writing an XML with each attributes on separate lines

# Note, I am purposefully using the non-desired output as an input.
$xml = [xml]@'
<BackendSystemSettings>
    <Backend a ="123" b="ABC" c="ABC123"/>
    <Backend a ="456" b="DEF" c="DEF456"/>
</BackendSystemSettings>
'@

Function  Export-XML {
    [CmdletBinding()]
    Param($xml, $Path)
    # XMLWriter Settings ... Where the magic happen
    $settings = [system.Xml.XmlWriterSettings]::new()
    # Use the parameters you need 
    $settings.OmitXmlDeclaration = $true 
    $settings.NewLineOnAttributes = $true
    $settings.Indent = $true

    $writer = [System.Xml.XmlWriter]::Create($Path, $settings)
    $xml.Save($writer)
    $Writer.Dispose()
}

# Do whatever modifications you wish to perform... 
$xml.BackendSystemSettings.Backend[0].a = 'Modified !!!!'

# Here we call our new function to save the XML 
Export-XML -xml $xml -Path 'C:\temp\test\71376785.xml'

Resulting output

<BackendSystemSettings>
  <Backend
    a="Modified !!!!"
    b="ABC"
    c="ABC123" />
  <Backend
    a="456"
    b="DEF"
    c="DEF456" />
</BackendSystemSettings>

References:

XmlWriterSettings Class

  • Related