【发布时间】:2021-03-25 03:43:21
【问题描述】:
我正在尝试将我的 xml-request(参见下面的示例)转换为 pandas-dataframe,但它没有按应有的方式工作,我不知道为什么。
xml 请求示例
<workingTimes>
<day>
<date>2015-09-21</date>
<dayOfWeek>Mon</dayOfWeek>
<employee>
<firstName>Albert</firstName>
<lastName>Grimaldi</lastName>
<login xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
<personnelNumber xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
<duration>00:00:00</duration>
<rest mandatory="00:00:00">00:00:00</rest>
<costCenter>AB-1234</costCenter>
</employee>
<employee>
<firstName>Max</firstName>
<lastName>Mustermann</lastName>
<login xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
<personnelNumber>12346</personnelNumber>
<duration>00:00:00</duration>
<rest mandatory="00:00:00">00:00:00</rest>
<costCenter>AB-1234</costCenter>
</employee>
</day>
<day>
<date>2015-09-22</date>
<dayOfWeek>Tue</dayOfWeek>
<employee>
<firstName>Albert</firstName>
<lastName>Grimaldi</lastName>
<login xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
<personnelNumber xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
<duration>00:00:00</duration>
<rest mandatory="00:00:00">00:00:00</rest>
<costCenter>AB-1234</costCenter>
</employee>
<employee>
<firstName>Max</firstName>
<lastName>Mustermann</lastName>
<login xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
<personnelNumber>12346</personnelNumber>
<duration>00:00:00</duration>
<rest mandatory="00:00:00">00:00:00</rest>
<costCenter>AB-1234</costCenter>
</employee>
</day>
</workingTimes>
代码:
import pandas as pd
from xml.etree import ElementTree as et
...
r = requests.get(api_url, headers=headers)
root = et.fromstring(r.content)
df_cols, rows = ['date', 'dayOfWeek', 'firstName', 'lastName', 'duration', 'costCenter'], []
for child in root:
s_date = child.attrib.get("date")
s_dayOfWeek = child.attrib.get("dayOfWeek")
s_firstName = child.find("firstName").text if child is not None else None
s_lastName = child.find("lastName").text if child is not None else None
s_duration= child.find("duration").duration if child is not None else None
s_costCenter= child.find("costCenter").text if child is not None else None
rows.append({'date': s_date, 'dayOfWeek': s_dayOfWeek, 'firstName': s_firstName, 'lastName':
s_lastName, 'duration': s_duration, 's_costCenter': costCenter})
df_xml = pd.DataFrame(rows, columns=df_cols)
谁能告诉我我做错了什么?
【问题讨论】:
-
有什么问题?请注意,
date和dayOfWeek与您要查找的属性不在同一级别。 -
@balderman 我得到一个空的数据框,即使我知道我的 xml 中有条目!这就像我无法进入子元素(是这样称呼的吗?)。
-
首先测试我发布的代码并填充 df。如果它有效 - 扩展它。
标签: python xml dataframe elementtree