Search code examples
pythonxmlminidom

Get Document from Node or Element objects with minidom


Is there a way I can get the document root from a child Element or Node? I am migrating from a library that works with any of Document, Element or Node to one that works only with Document. eg.

From:

element.xpath('/a/b/c') # 4Suite

to:

xpath.find('/a/b/c', doc) # pydomxpath

Solution

  • Node objects have an ownerDocument property that refers to the Document object associated with the node. See http://www.w3.org/TR/DOM-Level-2-Core/core.html#node-ownerDoc.

    This property is not mentioned in the Python documentation, but it's available. Example:

    from xml.dom import minidom
    
    XML = """
    <root>
       <x>abc</x>
       <y>123</y>
    </root>"""
    
    dom = minidom.parseString(XML)
    x = dom.getElementsByTagName('x')[0]
    
    print x
    print x.ownerDocument
    

    Output:

    <DOM Element: x at 0xc57cd8>
    <xml.dom.minidom.Document instance at 0x00C1CC60>