在Python中解析第二个XML元素

2024-10-16 17:24:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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下的标记。找到这个元素的最佳方法是什么?你知道吗


Tags: itemcountryregionxxxxxcategoryxxxxxxjobtitleemployeename
3条回答

看起来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

只需添加另一个循环,如下所示。我的缩进也可能会掉。你知道吗

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)

要访问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']

相关问题 更多 >