How to split xml file into smaller files using powershell?

by hal.littel , in category: Third Party Scripts , 2 months ago

How to split xml file into smaller files using powershell?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 2 months ago

@hal.littel 

One way to split an XML file into smaller files using PowerShell is to read the original XML file, loop through its nodes, and then write each node to a new file.


Here is an example script that demonstrates this process:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
$sourceFile = "original.xml"
$destinationFolder = "output"

# Load the original XML file
[xml]$xml = Get-Content $sourceFile

# Create the output folder if it does not exist
if (-not (Test-Path $destinationFolder)) {
    New-Item -ItemType Directory -Path $destinationFolder
}

# Loop through each node in the XML file
foreach ($node in $xml.DocumentElement.ChildNodes) {
    # Create a new XML document with only the current node
    $newXml = New-Object System.Xml.XmlDocument
    $newNode = $newXml.ImportNode($node, $true)
    $newXml.AppendChild($newNode)

    # Save the new XML document to a file
    $fileName = Join-Path $destinationFolder "$($node.LocalName).xml"
    $newXml.Save($fileName)
}


To use this script, save the code to a PowerShell script file (e.g., splitXml.ps1) and then run it in a PowerShell console. Make sure to replace "original.xml" with the path to your XML file. This script will create a folder named "output" in the same directory as the script and save each node of the original XML file as a separate XML file in that folder.