我有一个树层次结构 xml 列表,我的目标是迭代它并创建三个字典列表 grantparent、parent、child 像这样 [{[key:value],..}{}]。
<Grandparent>
<Name>Zavulon</Name>
<age earthage = "80">4600</age>
<height>342</height>
<Parent>
<name>Dan</name>
<name>Daniel</name>
<height>210</height>
<Child>
<name>XO</name>
<name earthname = "Bob">Tringomurro</name>
</Child>
</Parent>
</Grandparent>
这是一个例子。真正的列表要大得多,我不知道所有属性名称,所以我认为我需要编写另一个与迭代分开的函数来检查属性并将它们作为字符串连接到值变量或创建另一个键:值。
class Scanner():
def __init__(self):
self.dbxml = etree.parse('systems.xml')
self.sysinfo = []
self.starinfo = []
self.bodyinfo = []
def attr_check(self,tag,text): # here i need to check the tag for attributes, .join it to text and than return back
self.tag = tag
self.text = text
#!!! here i want to get attribute and assign new values but don't know how
return self.tag, self.text
def get_fields(self): # This method should create a dictionary for each planet,star or system
for system in self.dbxml.xpath('/systems/system'):
stm = {}
sn = {}
bd = {}
for star in system:
#here is where i call function
checkstar = attr_check(star.tag, star.text)
stm[checkstar[0]] = checkstar[1]
for sun in star:
#I'd like to call it here too
sn[sun.tag] = sun.text
for body in sun:
#And here
bd[body.tag] = body.text
self.bodyinfo.append(bd)
self.starinfo.append(sn)
self.sysinfo.append(stm)
return self.sysinfo, self.starinfo, self.bodyinfo
问题是 key.tag 没有属性,如果我在迭代函数中打印它并且我不知道如何触摸它。 因此,其中一个列表的输出应类似于 [{ Name: Zavulon,age : 4600 Earthage = 80}, ...] 或使 "earthage = "80""成为另一个键:值对。
附注我知道整个概念还不完美。一些口述。成对覆盖其他的,我会尝试自己管理它,如果你愿意给我一个提示,那就太好了。 (我是业余爱好者:)
最佳答案
找到了!要从 xml 获取 key:value 属性,我应该在迭代时使用 .attrib (而不是 .tag)。不需要检查功能:)干杯!
关于python - 如何迭代 xml 文件,检查 lxml 属性是否存在并将其及其值连接到另一个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31603675/