What is the difference between a ElementTree and an Element? (python xml)

末鹿安然 提交于 2021-01-21 08:06:20

问题


from xml.etree.ElementTree import ElementTree, Element, SubElement, dump

elem = Element('1')
sub = SubElement(elem, '2')
tree = ElementTree(elem)

dump(tree)
dump(elem)

In the code above, dumping tree (which is an ElementTree) and dumping elem (which is an Element) results in the same thing. Therefore I am having trouble determining what the difference is between the two.


回答1:


dumping tree (which is an ElementTree) and dumping elem (which is an Element) results in the same thing.

dump() function works the same for ElementTree and Element because it was intentionally made to behave this way:

def dump(elem):
    # debugging
    if not isinstance(elem, ElementTree):
        elem = ElementTree(elem)
    elem.write(sys.stdout)
    ...

I am having trouble determining what the difference is between the two.

ElementTree is a wrapper class that corresponds to the "entire element hierarchy" providing serialization functionality - dumping and loading the tree. Element, on the other hand, is a much "bigger" class that defines the Element interface.




回答2:


The ElementTree wrapper class is used to read and write XML files [ref]. Most ElementTree apis are simple wrappers around the root Element [ref]. Simply put, ElementTree wraps the root Element (for convenience) and provides methods to serialize/deserialize the entire tree. Hence parse() belongs to ElementTree where iter() is a simple wrapper.

Then there are helper functions like iterparse and dump() in the xml.etree.ElementTree namespace. dump() writes a full xml doc to stdout [ref] whereas iterparse spits out Elements iteratively. Contrast parse(), which returns an xml.etree.ElementTree.ElementTree object and hence a complete hierarchy, to iterparse(), which returns an iterator[1].

1 There might be some confusion between xml.etree.ElementTree package namespace and xml.etree.ElementTree.ElementTree class name.



来源:https://stackoverflow.com/questions/30813156/what-is-the-difference-between-a-elementtree-and-an-element-python-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!