使用Python从XML中提取标签
我有一个员工数据的文件,叫做 employeedata.xml。我的示例数据大概是这样的:
<?xml version="1.0" standalone="yes"?>
<DocumentElement>
<_x005B_dbo_x005D_._x005B_employeedata_x005D_>
<RowID>11148</RowID>
<ItemID>966109</ItemID>
<Mappings>[]</Mappings>
<Groups>93664,68349</Groups>
<GroupKey>7003142</GroupKey>
<ParentItemID>351908</ParentItemID>
<JobID>30318</JobID>
<Action>Employee</Action>
<Employee_Name>John Travis</Employee_Name>
<mail_id>John@altmail.com</mail_id>
<...>...</...>
<Action>Experience</Action>
<...>...</...>
<...>...</...>
<...>...</...>
我正在使用 Python 3.8.10 来读取这个文件。我用下面的代码来读取我的数据:
with open('employeedata.xml', 'r') as f:
data = f.read()
我想把我的 XML 数据存储到一个 pandas 数据框里,其中标签 Action
下的值会存放在 Action
这一列,而对应的标签会存放在另一列 Field
。我的示例输出大概是这样的:
| Action | Field |
|--------------|-------------|
| Employee |Employee_Name|
| Employee |mail_id |
| Employee |.... |
| Employee |.... |
| Experience|.... |
| Experience|.... |
你能告诉我该怎么做吗?
2 个回答
0
Pandas可以直接读取xml文件:
import pandas as pd
df = pd.read_xml("Employee data.xml", xpath="_x005B_dbo_x005D_._x005B_employeedata_x005D_")
print(df[['Action', 'Employee_Name']].to_string(index=False))
如果你愿意,也可以把整个内容打印出来。
输出结果:
Action Employee_Name
Experience John Travis
0
你可能在找这个 Python的XML解析模块
在你的情况下:
import xml.etree.ElementTree as ET
tree = ET.parse('employeedata.xml')
root = tree.getroot()