title: Split XML by node
body: <p>I've got a big XML file (more than 4Gb) and i should integrate it into SQL table.
  SQL has a 2 Gb limitation. The idea is to split the file into serveral XML. For example 500Mb by file.</p>
  <p>I try to adapt a powershell script but i still have the following error</p>
  <p><a href="https://i.stack.imgur.com/9gleu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9gleu.png" alt="enter image description here" /></a></p>
  <p>Here is the PowerShell script i'm using and i can't find what's wrong</p>
  <pre><code>param(  [string]$file = $(throw &quot;ENTITY.XML&quot;), $matchesPerSplit = 50, $maxFiles = [Int32]::MaxValue, $splitOnNode = $(throw &quot;entity&quot;), $offset = 0 )
  
  $ErrorActionPreference = &quot;Stop&quot;;
  
  trap {
      $ErrorActionPreference = &quot;Continue&quot;
      write-error &quot;Script failed: $_ \r\n $($_.ScriptStackTrace)&quot;
      exit (1);
  }
  
  $file = (resolve-path $file).path
  
  $fileNameExt = [IO.Path]::GetExtension($file)
  $fileNameWithoutExt = [IO.Path]::GetFileNameWithoutExtension($file)
  $fileNameDirectory = [IO.Path]::GetDirectoryName($file)
  
  
  $reader = [System.Xml.XmlReader]::Create($file) 
   
  $matchesCount = $idx = 0
  
  try {
      &quot;Splitting $from on node name='$splitOnNode', with a max of $matchesPerSplit matches per file. Max of $maxFiles files will be generated.&quot;
      $result = $reader.ReadToFollowing($splitOnNode)
      $hasNextSibling = $true
      while (-not($reader.EOF) -and $result -and $hasNextSibling -and ($idx -lt $maxFiles + $offset)) {
          if ($matchesCount -lt $matchesPerSplit) {
              if($offset -gt $idx) {
                 $idx++
                 continue
              }
          
              $to = [IO.Path]::Combine($fileNameDirectory, &quot;$fileNameWithoutExt.$($idx -$offset)$fileNameExt&quot;)
              &quot;Writing to $to&quot;
              $toXml = New-Object System.Xml.XmlTextWriter($to, $null)
              $toXml.Formatting = 'Indented'
              $toXml.Indentation = 2
              try {
                 $toXml.WriteStartElement(&quot;split&quot;)
                 $toXml.WriteAttributeString(&quot;cnt&quot;, $null, &quot;$idx&quot;)
                 
                 do {
                    $toXml.WriteRaw($reader.ReadOuterXml())
                    $matchesCount++;
                    $hasNextSibling = $reader.ReadToNextSibling($splitOnNode)
                 } while($hasNextSibling -and ($matchesCount -lt $matchesPerSplit))
                 $toXml.WriteEndElement();
              } 
              finally {
                 $toXml.Flush()
                 $toXml.Close()
              }
              $idx++
              $matchesCount = 0;
          }
      }
  }
  finally {
      $reader.Close()
  }
  
  </code></pre>
  <p>My XML file is on the same folder as the PS file and &quot;entity&quot; is the node.</p>