You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell实现CSV转XML:按指定数量拆分XML文件求助

PowerShell: Split XML Output into Multiple Files Every N Elements

I get it—you’re trying to generate XML files from a CSV, but need to split them into chunks every X <Document> elements, and your current counter setup only keeps the last batch. Let’s fix that with a structured approach that properly resets the XML document and saves each batch as it’s completed.

Step-by-Step Solution

First, let’s outline the core logic:

  • Read the CSV data
  • Track how many <Document> elements we’ve added to the current XML
  • When we hit your specified batch size (e.g., 3), save the XML file, reset the counter, and start a new XML document
  • Don’t forget to save any remaining elements after processing all CSV rows

Full Working Script

param(
    [Parameter(Mandatory=$true)]
    [string]$InputCsvPath,
    
    [string]$OutputXmlPrefix = "document_batch_",
    
    [int]$BatchSize = 3
)

# Import CSV data
$csvRecords = Import-Csv -Path $InputCsvPath

# Initialize counters and XML structure
$currentDocumentCount = 0
$currentBatchNumber = 1

# Create the initial XML document with root element
$xmlDocument = New-Object System.Xml.XmlDocument
$rootElement = $xmlDocument.CreateElement("Documents")
$xmlDocument.AppendChild($rootElement) | Out-Null

foreach ($record in $csvRecords) {
    # Create a new <Document> element for the CSV row
    $documentElement = $xmlDocument.CreateElement("Document")
    
    # Add each CSV column as a child element to <Document>
    foreach ($property in $record.PSObject.Properties) {
        $childElement = $xmlDocument.CreateElement($property.Name)
        $childElement.InnerText = $property.Value
        $documentElement.AppendChild($childElement) | Out-Null
    }
    
    # Add the <Document> to the current XML root
    $rootElement.AppendChild($documentElement) | Out-Null
    $currentDocumentCount++
    
    # Check if we've reached the batch size
    if ($currentDocumentCount -eq $BatchSize) {
        # Save the current batch to file
        $outputFilePath = "$OutputXmlPrefix$currentBatchNumber.xml"
        $xmlDocument.Save($outputFilePath)
        Write-Host "Successfully saved batch $currentBatchNumber to $outputFilePath"
        
        # Reset for next batch
        $currentDocumentCount = 0
        $currentBatchNumber++
        
        # Create a fresh XML document for the next batch
        $xmlDocument = New-Object System.Xml.XmlDocument
        $rootElement = $xmlDocument.CreateElement("Documents")
        $xmlDocument.AppendChild($rootElement) | Out-Null
    }
}

# Save any remaining records that didn't fill a full batch
if ($currentDocumentCount -gt 0) {
    $outputFilePath = "$OutputXmlPrefix$currentBatchNumber.xml"
    $xmlDocument.Save($outputFilePath)
    Write-Host "Successfully saved final batch $currentBatchNumber (with $currentDocumentCount documents) to $outputFilePath"
}

Key Fixes & Improvements Over Your Original Code

  1. Proper XML Reset: Instead of modifying a single XML document throughout, we create a new XmlDocument object for each batch. This eliminates the issue of leftover elements from previous batches.
  2. Batch Trigger Logic: The counter ($currentDocumentCount) increments with each <Document> element, and when it hits $BatchSize, we immediately save the file and reset. No more losing intermediate batches!
  3. Final Batch Handling: After the loop finishes, we check if there are any unsaved documents (fewer than the batch size) and save them to a final file.
  4. Parameterization: The script uses parameters for input path, output prefix, and batch size, making it flexible for different use cases.

Example Usage

Suppose your CSV (input.csv) looks like this:

ID,Name,Department
1,John Doe,Engineering
2,Jane Smith,Marketing
3,Bob Brown,Finance
4,Sarah Lee,Engineering
5,Mike Chen,HR

Running the script:

.\SplitCsvToXml.ps1 -InputCsvPath "input.csv" -OutputXmlPrefix "company_docs_" -BatchSize 3

You’ll get two XML files:

  • company_docs_1.xml (contains the first 3 <Document> elements)
  • company_docs_2.xml (contains the remaining 2 <Document> elements)

Each XML file will have a root <Documents> element wrapping the <Document> entries, like this:

<Documents>
  <Document>
    <ID>1</ID>
    <Name>John Doe</Name>
    <Department>Engineering</Department>
  </Document>
  <!-- Two more documents here for batch 1 -->
</Documents>

Why Your Original Counter Failed

Chances are, you were reusing the same XML document without resetting it, or only saving the file once at the end of the loop. By creating a new XML document for each batch and saving immediately when the counter hits the threshold, we ensure each batch is preserved correctly.

内容的提问来源于stack exchange,提问作者Hadrien Beaujean

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 13:07:34