解析Python中的第二个XML元素

时间:2018-08-13 20:26:15

标签: python xml parsing

我有以下格式的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>

我能够使用

来解析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下检索标签。什么是到达此元素的最佳方法?

3 个答案:

答案 0 :(得分:0)

只需添加另一个如下所示的循环即可。另外,我的缩进可能不正确。

for item in root.findall('item'):
row = []
if item.find('Category') is not None:
    category = item.find('Category').text
else:
     for itemsecond in root.findall('WorkerInfo'):
         if item.find('WorkerInfo') is not None:
             category2= item.find('Category').text
             if category2 is not None:
                row.append(category2)
row.append(category)

答案 1 :(得分:0)

看起来好像WorkerInfo包含嵌套的元素,并且您的第一行for item in foot.findall('item'):仅在顶级元素上循环。因此,在某个时候,item将被设置为WorkerInfo,但这与对其子元素的设置不同。您将需要一个嵌套循环来遍历这些循环。试试这个:

for item in root.findall('item'):
    for workerItem in item.findall('WorkerInfo'):
        // Do whatever you want with the elements of WorkerInfo here

答案 2 :(得分:0)

要进入WorkerInfo并检索其标签,可以使用类似的结构。只需调用findall()并传入'WorkerInfo'并遍历其子代即可。

for item in root.findall('item'):
    for worker in root.findall('WorkerInfo'):
        row = []
        for child in worker:
            row.append(child.tag)

以您的示例为例,row变为['Country', 'JobTitle', 'Region']