Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 519
Himanshu Avatar asked Mar 27 '26 23:03

Himanshu


1 Answers

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>
like image 144
mzjn Avatar answered Mar 29 '26 16:03

mzjn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!