Python - abstracting recursion to all n-th level recursion (lxml)

I have an almost identical XML that I am trying to compare and found this: Compare XML fragments? that pointed to this: https://bitbucket.org/ianb/formencode/src/tip/formencode/doctest_xml_compare.py#cl-70 I have a way to test two nodes.

The next step is to exit the node-based test, and if False , go to all the children and repeat the test.

I wrote Walker a long way that allows me to go through as many children as I want to write code for:

  if xml.xml_compare(a.root, b.root) == False: for i, node in enumerate(a.root): if xml.xml_compare(a.root[i], b.root[i]) == False: for j, node in enumerate(a.root[i]): if xml.xml_compare(a.root[i][j], b.root[i][j]) == False: for k, node in enumerate(a.root[i][j]): .... if xml.xml_compare(a.root[i][j][k][l][m][n], b.root[i][j][k][l][m][n]) == False: 

This is clearly not suitable for arbitrary XML size, and it is not very elegant. i thnk i need to write a generator to validate the xml test - i saw that itertool is a way to do this:

 class XML_Tools(object): .... def iterparent(self, xml_object): """ returns the parent and children of a node """ for parent in xml_object.getiterator(): for child in parent: yield self.parent, self.child main(): a = ET.parse(open(file_a, "r") b = ET.parse(open(file_b, "r") xml.iterparent(a.root) for xml.parent, xml.child in xml.iterparent(a.root): print xml.parent, xml.child 

But I could not find a way to get the work object xml.parent or xml.child that I can work with. I suspect that I have mixed up the function in the class, and I am not giving / not getting the right things.

What I want to do is find the source of the False comparison and print two offensive data elements and find out where they live (or are absent) in two parts of XML.

+4
source share
1 answer

I would suggest using a recursive algorithm that takes a list of 2 elements for comparison and the pass number as arguments. You will need a dictionary defining the list that will be delivered on each pass. You can also write an algorithm to create a dictionary of n elements, hope this helps. I could try and give a code example if it were more useful.

EDIT:

 n=3 ##Depth of tree d={'0':['a.root', 'b.root', 0]} for i in range(n): d[str(i+1)]=[d[str(i)][0]+'['+chr(105+i)+']', #since ord('i')=105, start d[str(i)][1]+'['+chr(105+i)+']', # at i, j, k, etc i+1 #passNo ] print(d) def compare(points=d['0'], passNo=0): if xml.xml_compare(eval(points[0]), eval(points[1])) == False: exec('for'+str(chr(points[2]+105))+'in enumerate('+str(points[0])+\ '): compare('+str(d[str(passNo+1)][0])+', '+str(d[str(passNo+1)][1])+')') compare() 

I apologize for the mess of code, but I think it will do what you want. However, I cannot verify it without knowing how you imported the xml modules / content or which xml objects you use. Hope this helps.

+3
source

Source: https://habr.com/ru/post/1499701/


All Articles