这是描述表单的XML文件的一部分:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfHouse>
<XmlForm>
<houseNum>1</houseNum>
 <plan1>
  <coord>
    <X> 1.2  </X>
    <Y> 2.1  </Y>
    <Z> 3.0  </Z>
  </coord>
  <color>
    <R> 255 </R>
    <G> 0   </G>
    <B> 0   </B>
  </color>
 </plan1>
 <plan2>
  <coord>
    <X> 21.2  </X>
    <Y> 22.1  </Y>
    <Z> 31.0  </Z>
  </coord>
  <color>
    <R> 255 </R>
    <G> 0   </G>
    <B> 0   </B>
</color>
 </plan2>
</XmlForm>


<XmlForm>
<houseNum>2</houseNum>
 <plan1>
  <coord>
    <X> 11.2  </X>
    <Y> 12.1  </Y>
    <Z> 13.0  </Z>
  </coord>
  <color>
    <R> 255 </R>
    <G> 255   </G>
    <B> 0   </B>
  </color>
 </plan1>
 <plan2>
  <coord>
    <X> 211.2  </X>
    <Y> 212.1  </Y>
    <Z> 311.0  </Z>
  </coord>
  <color>
    <R> 255 </R>
    <G> 0   </G>
    <B> 255   </B>
</color>
 </plan2>
</XmlForm>
</ArrayOfHouse>


这是我的代码,用于调补房屋1和2的每个计划的坐标,问题在此行coord=tree.findall("XmlForm/[houseNum=str(houseindex)]中,使用houseindex.__str__()时也会出现相同的问题

import pandas as pd
import numpy as np
from lxml import etree
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
tree =etree.parse("myexample.xml")
#recuperate the columns name for pandas dataframe
planlist=tree.findall("XmlForm/[houseNum='1']/")

columns=[]

for el in planlist[1:]:
    columns.append(el.tag)

#Declare pandas dataFrame
df=pd.DataFrame(columns=list('XYZ'),dtype=float)
for houseindex in range(0,2):
    for index in range(len(columns)):

        coord=tree.findall("XmlForm/[houseNum=str(houseindex)]/"+columns[index]+"/coord/")
        XYZ=[]
        for cc in coord:
            XYZ.append(cc.text)
        df.loc[index]=XYZ
print(df)

最佳答案

您不要在字符串中插入“ houseindex”。另外,在houseindex的for循环中也要小心,因为您当前使用的是对应于0和1的range(0,2)。基于您的xml示例,您宁愿使用range(1,3)。

我相信您想要这样的东西(我对您的代码进行了一些重构以提高可读性):

import pandas as pd
from lxml import etree

tree = etree.parse("myexample.xml")

# recuperate the columns name for pandas dataframe
plan_list = tree.findall("XmlForm/[houseNum='1']/")
columns = [el.tag for el in plan_list[1:]]

# Declare pandas dataFrame
data = list()
for house_index in range(1, 3):
    for column in columns:

        element_text = "XmlForm/[houseNum='{index}']/{column}/coord/".format(index=house_index, column=column)
        coord = tree.findall(element_text)
        row = [cc.text for cc in coord]
        data.append(row)

df = pd.DataFrame(data, columns=list('XYZ'), dtype=float)
print(df)

10-05 23:52