0

I am working on performing a breadth-first search (BFS) traversal on an XML File. A Depth First Search algorithm is shown in the https://lxml.de/3.3/api.html#lxml-etre. However, I need help with applying the BFS Search based on this code. Below is the code given in the documentation:

>>> 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

I need help with trying to append it to make it suitable for BFS Traversal. Below is an example of the code I tried to write but it doesn't work correctly. Can someone please help. My Code: from collections import deque

>>> d = deque([root])
>>> while d:
    >>> el = d.pop() 
    >>> d.extend(el)
    >>> print(el.tag)

Thank You

2 Answers2

0

Your implementation of BFS is currently popping from the wrong end of your queue. You should use popleft() rather than pop().

d = deque([root])
while d:
    el = d.popleft() 
    d.extend(el)
    print(el.tag)
0x263A
  • 1,807
  • 9
  • 22
  • Hi, Thank You for your reply. But I believe that the code you have written is Depth First (available already on the lxml website). I need Breadth-First Search. Can you please help with that? – Upatel2 Jul 23 '21 at 01:21
  • This prints the tree in the order of a breadth-first search. Perhaps you misunderstand BFS? @Upatel2 – 0x263A Jul 23 '21 at 01:31
  • @Upatel2 consider adding what your expected output is vs what you are getting. – 0x263A Jul 23 '21 at 01:35
  • Thank You. Yes, I may have confused myself a little. Appreciate your responses. – Upatel2 Jul 23 '21 at 07:16
0

Can be implemented with xpath also

>>> root = etree.XML('<root><a><b/><c><f/></c></a><d><e/></d></root>')
>>> queue = deque([root])
>>> while queue:
...     el = queue.popleft()
...     queue.extend(el.xpath('./child::*'))
...     print(el.tag)
... 
root
a
d
b
c
e
f
LMC
  • 10,453
  • 2
  • 27
  • 52