bandit/examples/xml_sax.py
Ian Cordasco 4af7ea6a20 Update example files to work on Python 2 & 3
Almost all of the problems were using print statements instead of
equivalent Python 3 syntax. You'll notice that in Python 2, the AST
parses `print(...)` and `print ...` equivalently:

    $ python
    Python 2.7.9 (default, Dec 15 2014, 10:01:34)
    [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import ast
    >>> body = ast.parse('print("Foo")').body[0]
    >>> body
    <_ast.Print object at 0x1033452d0>
    >>> body.values
    [<_ast.Str object at 0x103345310>]
    >>> body2 = ast.parse('print "Foo"').body[0]
    >>> body2
    <_ast.Print object at 0x103345350>
    >>> body2.values
    [<_ast.Str object at 0x103345390>]

This leaves 2 files - exec.py, os-chmod.py - which are skipped due to
syntax errors on Python 3.4.

Change-Id: I2d97a249503317092372a874c018561cf875b066
2015-06-03 16:28:36 +00:00

38 lines
1.0 KiB
Python

import xml.sax
from xml import sax
import defusedxml.sax
class ExampleContentHandler(xml.sax.ContentHandler):
def __init__(self):
xml.sax.ContentHandler.__init__(self)
def startElement(self, name, attrs):
print('start:', name)
def endElement(self, name):
print('end:', name)
def characters(self, content):
print('chars:', content)
def main():
xmlString = "<note>\n<to>Tove</to>\n<from>Jani</from>\n<heading>Reminder</heading>\n<body>Don't forget me this weekend!</body>\n</note>"
# bad
xml.sax.parseString(xmlString, ExampleContentHandler())
xml.sax.parse('notaxmlfilethatexists.xml', ExampleContentHandler())
sax.parseString(xmlString, ExampleContentHandler())
sax.parse('notaxmlfilethatexists.xml', ExampleContentHandler)
# good
defusedxml.sax.parseString(xmlString, ExampleContentHandler())
# bad
xml.sax.make_parser()
sax.make_parser()
print('nothing')
# good
defusedxml.sax.make_parser()
if __name__ == "__main__":
main()