如何检查 lxml 元素树字符串?

how to check lxml element tree strings?

我有 lxml 个元素树的列表。我想在字典中存储子树出现在树列表的任何子树中的次数。例如

tree1='''<A attribute1="1"><B><C/></B></A>'''
tree2='''<A attribute1="1"><D><C attribute="2"/></D></A>'''
tree3='''<E attribute1="1"><B><C/></B></E>'''
list_trees=[tree1,tree2,tree3]
print list_trees
from collections import defaultdict
from lxml import etree as ET
mydict=defaultdict(int) 
for tree in list_trees:
    root=ET.fromstring(tree)
    for sub_root in root.iter():
        print ET.tostring(sub_root)
        mydict[ET.tostring(sub_root)]+=1
print mydict

我得到以下正确结果:

defaultdict(<type 'int'>, {'<E attribute1="1"><B><C/></B></E>': 1, '<C/>': 2, '<A attribute1="1"><D><C attribute="2"/></D></A>': 1, '<B><C/></B>': 2, '<C attribute="2"/>': 1, '<D><C attribute="2"/></D>': 1, '<A attribute1="1"><B><C/></B></A>': 1})

这只适用于这个特定的例子。但是,在一般情况下,xmls 可以相同但具有不同的属性顺序,或者额外的空格或无关紧要的换行符。但是,这种一般情况会破坏我的系统。我知道有关于如何检查 2 个相同的 xml 树的帖子,但是,我想将 xml 转换为字符串以执行上述特定应用程序(轻松保持独特的树因为字符串允许在未来进行简单的比较和更大的灵活性)并且还能够很好地将它存储在 sql 中。 xml 如何以一致的方式变成字符串,而不考虑顺序、额外的空格、额外的行?

编辑给出不起作用的案例: 这 3 棵 xml 树是相同的,它们只是属性或额外空格或换行的顺序不同。

tree4='''<A attribute1="1" attribute2="2"><B><C/></B></A>'''
tree5='''<A attribute1="1"     attribute2="2"   >
<B><C/></B></A>'''
tree6='''<A attribute2="2" attribute1="1"><B><C/></B></A>'''

我的输出如下:

defaultdict(<type 'int'>, {'<B><C/></B>': 3, '<A attribute1="1" attribute2="2"><B><C/></B></A>': 1, '<A attribute1="1" attribute2="2">\n<B><C/></B></A>': 1, '<C/>': 3, '<A attribute2="2" attribute1="1"><B><C/></B></A>': 1})

然而,输出应该是:

defaultdict(<type 'int'>, {'<B><C/></B>': 3, '<A attribute1="1" attribute2="2"><B><C/></B></A>': 3, '<C/>': 3})

如果你坚持比较XML树的字符串表示,我建议在lxml之上使用BeautifulSoup。特别是,在树的任何部分调用 prettify() 会创建一个独特的表示,忽略输入中的空格和奇怪的格式。输出字符串有点冗长,但它们有效。我继续用 "fake newlines" ('\n' -> '\n') 替换换行符,因此输出更紧凑。

from collections import defaultdict
from bs4 import BeautifulSoup as Soup

tree4='''<A attribute1="1" attribute2="2"><B><C/></B></A>'''
tree5='''<A attribute1="1"     attribute2="2"   >
<B><C/></B></A>'''
tree6='''<A attribute2="2" attribute1="1"><B><C/></B></A>'''
list_trees = [tree4, tree5, tree6]

mydict = defaultdict(int)
for tree in list_trees:
    root = Soup(tree, 'lxml-xml') # Use the LXML XML parser.
    for sub_root in root.find_all():
        print(sub_root)
        mydict[sub_root.prettify().replace('\n', '\n')] += 1

print('Results')
for key, value in mydict.items():
    print(u'%s: %s' % (key, value))

打印出所需的结果(带有一些额外的换行符和空格):

$pythoncounter.py

<A attribute1="1" attribute2="2">\n <B>\n  <C/>\n </B>\n</A>: 3
<B>\n <C/>\n</B>: 3
<C/>\n: 3