Reputation: 125
A question about testing proper nesting of XML tags:
I got a list of tags, extracted from top to bottom from an xml file:
tag_list = ['note', 'to', 'firstname', '/firstname', 'lastname', '/to', '/lastname', '/note']
What would be the code or direction to spot that /lastname tag is outside of its parent which is to, /to pair?
Cheers.
Upvotes: 0
Views: 92
Reputation: 41135
Make an empty stack.
Upvotes: 1
Reputation: 76346
Remove the backslashes, iterate on the reversed version, and compare with the original.
E.g., this will give you the indices of discrepancy:
wo = [tag[1: ] if tag and tag[0] == '/' else tag for tag in taglist]
rev = list(reversed(wo))
discrepancies = [i for i in xrange(len(wo)) if wo[i] != rev[i]]
Upvotes: 2