[lxml-dev] DOM tree intersection/comparison?

Stefan Behnel stefan_ml at behnel.de
Mon May 26 22:06:05 CEST 2008


Stefan Behnel wrote:
> Viksit Gaur wrote:
>> I see there's a DFS
>> iterator for elements, but is there a way to do a breadth first
>> iteration through the tree?
> 
> there's no API for it, but BFS shouldn't be that hard to do in Python.
> Actually, if deque() supported appending during iteration, it would be totally
> trivial. But there should be recipes on the web.

I added a simple BFS recipe to the iteration section of api.txt:

    >>> root = etree.XML('<root><a><b/><c/></a><d><e/></d></root>')
    >>> print(etree.tostring(root, pretty_print=True, encoding=unicode))
    <root>
      <a>
        <b/>
        <c/>
      </a>
      <d>
        <e/>
      </d>
    </root>

    >>> queue = deque([root])
    >>> while queue:
    ...    el = queue.popleft()  # pop next element
    ...    queue.extend(el)      # append its children
    ...    print(el.tag)
    root
    a
    d
    b
    c
    e


Stefan




More information about the lxml-dev mailing list