我有一个XML文件,格式如下:
<item id="xxxxxx">
<Category>xxxxx</Category>
<EmpEmail>xxxxxx</EmpEmail>
<EmployeeName>xxxxxxx</EmployeeName>
<InteractionType>xxxxxx</InteractionType>
<pxCreateOpName>xxxxxx</pxCreateOpName>
<pyID>xxxxx</pyID>
<WorkerInfo>
<Country>xxxxx</Country>
<JobTitle>xxxxxx</JobTitle>
<Region>xxxxx</Region>
</WorkerInfo>
<InsKey>xxxxx</InsKey>
</item>
我可以使用
for item in root.findall('item'):
row = []
if item.find('Category') is not None:
category = item.find('Category').text
else:
category = ''
row.append(category)
但是我无法使用for item in root.findall('WorkerInfo')
检索WorkerInfo下的标记。找到这个元素的最佳方法是什么?你知道吗
看起来WorkerInfo包含嵌套元素,第一行
for item in foot.findall('item'):
将只在顶级元素上循环。因此,在某个时刻item
将被设置为WorkerInfo,但这与设置为其子元素不同。您将需要一个嵌套的循环来循环这些。试试这个:只需添加另一个循环,如下所示。我的缩进也可能会掉。你知道吗
要访问
WorkerInfo
并检索其标记,可以使用类似的结构。只需调用findall()
传入'WorkerInfo'
并循环遍历其子级。你知道吗在您的示例中,
row
变成['Country', 'JobTitle', 'Region']
相关问题 更多 >
编程相关推荐