Search code examples
pythonxmlminidom

Cannot call xml.dom.minidom.parse inside class


I am unable to call xml.dom.minidom.parse() within my class

As a sheer example,

class XmlReader:
   def __init__(self, xml):
      self.xml = xml 
      DOMTree = xml.dom.minidom.parse("test.xml")

xmlReader = XmlReader("test.xml")

Throws

File "handler2.py", line 10, in ?
    xmlReader = XmlReader("test.xml")
  File "handler2.py", line 8, in __init__
    DOMTree = xml.dom.minidom.parse("test.xml")
AttributeError: 'str' object has no attribute 'dom'

However outside I am able to call xml.dom.minidom.parse just fine.

What do I need to change in order to be able to call the function within my XmlReader class?


Solution

  • Inside your constructor, xml refers to the parameter xml instead of the module xml. This is called shadowing. Choose a different name for one of them.

    import xml as xml_module
    

    or

    from xml.dom import minidom
    

    or

    def __init__(self, xml_data):