Indent_XML_HTML_PowerShell

Snippet Name: Indent_XML_HTML_PowerShell

Tags:

Created Date: 2025-06-16 13:12:45
Last Modified Date: 2025-05-31 10:32:05

Dependencies:

DBA Notes:

Sample Output:

Title: Indent XML HTML PowerShell
Author: user
I have an xml document that only contained Carriage Return and Line Feeds in the data elements...it is hard to read and organize. Pleas help me write a PowerShell function that indents xml/html tags.

Author: ChatGPT
Here's a PowerShell function that properly indents XML/HTML tags, making your document easier to read. It loads the XML, normalizes whitespace, and outputs the formatted XML with proper indentation.

### Features:
- Reads an XML/HTML file or a string.
- Removes unnecessary carriage returns and line feeds inside elements.
- Indents elements for better readability.

#### PowerShell Function:
```powershell
function Format-Xml {
    param (
        [Parameter(Mandatory=$true)]
        [string]$InputFile,

        [string]$OutputFile = $null
    )

    try {
        # Read the file content
        $xmlContent = Get-Content -Path $InputFile -Raw

        # Load the XML into an XmlDocument
        $xml = New-Object System.Xml.XmlDocument
        $xml.LoadXml($xmlContent)

        # Create an XmlWriterSettings object for formatting
        $settings = New-Object System.Xml.XmlWriterSettings
        $settings.Indent = $true
        $settings.IndentChars = "  " # Two-space indentation
        $settings.OmitXmlDeclaration = $false
        $settings.NewLineChars = "`r`n"

        # Format the XML
        $stringWriter = New-Object System.IO.StringWriter
        $xmlWriter = [System.Xml.XmlWriter]::Create($stringWriter, $settings)
        $xml.WriteContentTo($xmlWriter)
        $xmlWriter.Flush()
        $xmlWriter.Close()

        # Get the formatted XML as a string
        $formattedXml = $stringWriter.ToString()

        # Output to a file if specified
        if ($OutputFile) {
            $formattedXml | Set-Content -Path $OutputFile -Encoding UTF8
            Write-Host "Formatted XML saved to: $OutputFile"
        } else {
            return $formattedXml
        }
    }
    catch {
        Write-Error "Error processing XML file: $_"
    }
}
```

### How to Use:
#### Format and Output to Console:
```powershell
Format-Xml -InputFile "C:\path\to\yourfile.xml"
```

#### Format and Save to a File:
```powershell
Format-Xml -InputFile "C:\path\to\yourfile.xml" -OutputFile "C:\path\to\formatted.xml"
```

This function ensures that XML is properly structured, with correct indentation while preserving the XML declaration. Let me know if you need any modifications! ????


Leave a Reply