title: How to use xml sax parser to read and write a large xml?
body: <p>I'm trying to remove all the <code>project1</code> nodes (along with their child elements) from the below sample xml document (<em>original document is about 30 GB</em>) using SAX parser.It would be fine to have a separate modified file or ok with the in-line edit.</p>
  
  <p><code>sample.xml</code></p>
  
  <pre><code>&lt;ROOT&gt;
      &lt;test src="http://dfs.com"&gt;Hi&lt;/test&gt;
      &lt;project1&gt;This is old data&lt;foo&gt;&lt;/foo&gt;&lt;/project1&gt;
      &lt;bar&gt;
          &lt;project1&gt;ty&lt;/project1&gt;
          &lt;foo&gt;&lt;/foo&gt;
      &lt;/bar&gt;
  &lt;/ROOT&gt;
  </code></pre>
  
  <p>Here is my attempt..</p>
  
  <p><code>parser.py</code></p>
  
  <pre><code>from xml.sax.handler import ContentHandler
  import xml.sax
  
  class MyHandler(xml.sax.handler.ContentHandler):
      def __init__(self, out_file):
          self._charBuffer = []
          self._result = []
          self._out = open(out_file, 'w')
  
      def _createElement(self, name, attrs):
          attributes = attrs.items()
          if attributes:
              out = ''
              for key, value in attributes:
                  out += ' {}={}'.format(key, value)
              return '&lt;{}{}&gt;'.format(name, out)
          return '&lt;{}&gt;'.format(name)
  
  
      def _getCharacterData(self):
          data = ''.join(self._charBuffer).strip()
          self._charBuffer = []
          self._out.write(data.strip()) #remove strip() if whitespace is important
  
      def parse(self, f):
          xml.sax.parse(f, self)
  
      def characters(self, data):
          self._charBuffer.append(data)
  
      def startElement(self, name, attrs):
          if not name == 'project1': 
              self._result.append({})
              self._out.write(self._createElement(name, attrs))
  
      def endElement(self, name):
          if not name == 'project1': self._result[-1][name] = self._getCharacterData()
  
  MyHandler('out.xml').parse("sample.xml")
  </code></pre>
  
  <p>I can't make it to work.</p>