如何将XML转换为表格?

时间:2018-11-29 14:46:03

标签: python xml python-3.x dataframe

我正在从URL中获取XML字符串。这部分工作正常。

REQUEST_URL = 'https://URL'
response = requests.get(REQUEST_URL, auth=(login, password))
xml_data = response.text.encode('utf-8', 'ignore') 
tree = ET.parse(xml_data)
root = tree.getroot()

print(response.text) gives me:

<?xml version='1.0' standalone='yes'?><Report Type='SLA Report'
 SiteName='Execute Query'
 SLA_Name='Execute Query'
 SLA_Description='Execute Query'
 From='2018-11-27 00:00'
 Thru='2018-11-27 23:59' 
 obj_device='4500'
 locations='69,31,'
>
<Objective Type='Availability'>
<Goal>99.93</Goal>
<Actual>99.93</Actual>
<Compliant>Yes</Compliant>
<Errors>2</Errors>
<Checks>2878</Checks>
</Objective>
<Objective Type='Uptime'>
<Goal></Goal>
<Actual></Actual>
<Compliant></Compliant>
<Errors>0</Errors>
<Checks>0</Checks>
</Objective>
<Objective Type='Response Time'>
<Goal>300.00</Goal>
<Actual>3.1164</Actual>
<Compliant>Yes</Compliant>
<Errors>0</Errors>
<Checks>2878</Checks>
</Objective>
<MonitoringPeriods>
<Monitor>
<Exclude>No</Exclude><DayFrom>Sunday</DayFrom><TimeFrom>00:00</TimeFrom><DayThru>Sunday</DayThru><TimeThru>23:59</TimeThru>
</Monitor>

我想将数据放入表中,以便于使用。如何使用Python 3.x做到这一点?当我将其导入Excel时,它看起来很棒。

enter image description here

可能是这样的:

for sla in root.findall('Objective'):
    goal = sla.find('Goal').text
    actual = sla.find('Actual').text
    compliant = sla.find('Compliant').text
    errors = sla.find('Errors').text
    checks = sla.find('Checks').text
    print('Goal:', goal, 'Actual:', actual, 'Compliant:', compliant, 'Errors:', errors, 'Checks:', checks)

但是我想将每个数据点加载到一个数据帧中,而不是打印每个数据点。如何使用Python做同样的事情? TIA。

1 个答案:

答案 0 :(得分:0)

可以打印此:

enter image description here

# importing csv module 
import csv 

# csv file name 
filename = "aapl.csv"

# initializing the titles and rows list 
fields = [] 
rows = [] 

# reading csv file 
with open(filename, 'r') as csvfile: 
    # creating a csv reader object 
    csvreader = csv.reader(csvfile) 

    # extracting field names through first row 
    fields = csvreader.next() 

    # extracting each data row one by one 
    for row in csvreader: 
        rows.append(row) 

    # get total number of rows 
    print("Total no. of rows: %d"%(csvreader.line_num)) 

# printing the field names 
print('Field names are:' + ', '.join(field for field in fields)) 

# printing first 5 rows 
print('\nFirst 5 rows are:\n') 
for row in rows[:5]: 
    # parsing each column of a row 
    for col in row: 
        print("%10s"%col), 
    print('\n') 

来源:https://www.geeksforgeeks.org/working-csv-files-python/