如何用null填充缺失的属性值 | python |

How to fill the missing attribute value with null | python |

我一直在尝试实现逻辑,但不知道如何开始

我的 xml 如下数据,其中如果您将子根视为 3 个属性 如果缺少任何一个属性,在这种情况下应将其填充为 null

代码:

import xml.etree.ElementTree as ET

xml_data='''
<job_details>
    <role>
        <name>Vilan</name>
        <salary>.95</salary>
        <job_description>Developer</job_description>
    </role>
    <role>
        <name>Dils</name>
        <salary>.95</salary>
    </role>
    <role>
        <name>Raj</name>
        <job_description>Fullstack Developer</job_description>
    </role>
</job_details>
'''

get_root_element = ET.fromstring(xml_data)

out = []
for item in get_root_element:
    res = ','.join(x.text for x in item)
    out.append(res)

预期输出

['Vilan,.95,Developer', 'Dils,.95,null' , 'Raj',null,'Fullstack Developer'  ]

这里是你如何做到这一点。您需要定义所有字段,然后搜索它们。

编辑 正如在讨论的评论中,我在第 3 个角色中更改了你的 xml_dataname 字段现在存在但它没有值。

import xml.etree.ElementTree as ET

xml_data = """
<job_details>
    <role>
        <name>Vilan</name>
        <salary>.95</salary>
        <job_description>Developer</job_description>
    </role>
    <role>
        <name>Dils</name>
        <salary>.95</salary>
    </role>
    <role>
        <name></name>
        <job_description>Fullstack Developer</job_description>
    </role>
</job_details>
"""
out = []
get_root_element = ET.fromstring(xml_data)
all_fields = set([i.tag for role in get_root_element for i in role])
for item in get_root_element:
    tmp = []
    for fields in all_fields:
        res = item.find(fields)
        if res is not None:
            if res.text is not None:
                tmp.append(res.text)
            else:
                tmp.append("null")
        else:
            tmp.append("null")
    out.append(",".join(tmp))

print(out)

['Vilan,.95,Developer', 'Dils,.95,null', 'null,null,Fullstack Developer']