[issue15775] Add StopParser() to expat

Amaury Forgeot d'Arc report at bugs.python.org
Wed Sep 5 18:33:22 CEST 2012


Amaury Forgeot d'Arc added the comment:

Below is a sample script that shows that it's possible to stop parsing XML in the middle, without an explicit call to XML_StopParser(): raise StopParsing from any handler, and catch it around the Parse() call.

This method covers the two proposed use cases.  Do we need another way to do it?


import xml.parsers.expat

class StopParsing(Exception):
    pass

def findFirstElementByName(data, what):
  def end_element(name):
      if name == what:
          raise StopParsing(name)

  p = xml.parsers.expat.ParserCreate()
  p.EndElementHandler = end_element

  try:
      p.Parse(data, True)
  except StopParsing as e:
      print "Element found:", e
  else:
      print "Element not found"

data = """<?xml version="1.0"?>
         <parent id="top"><child1 name="paul">Text goes here</child1>
         <child2 name="fred">More text</child2>
         </parent>"""
findFirstElementByName(data, "child2")   # Found
findFirstElementByName(data, "child3")   # Not found

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue15775>
_______________________________________


More information about the Python-bugs-list mailing list