如何用python解析多层XML文件

如何用python解析多层XML文件,python,xml,parsing,lxml,Python,Xml,Parsing,Lxml,我有一个需要用python解析的多级XML文件,我有XML或lxml。如何解析?我找不到任何有用的解决方案。请帮助我,谢谢!理想情况下,我希望解析XML文件并转换为Python数据帧。 这个for循环不起作用 for child in root: for element in child: for element in child: print(element.tag, element.attrib) 这是我打印出来的结果的一部分 <

我有一个需要用python解析的多级XML文件,我有XML或lxml。如何解析?我找不到任何有用的解决方案。请帮助我,谢谢!理想情况下,我希望解析XML文件并转换为Python数据帧。 这个for循环不起作用

 for child in root:
     for element in child:
         for element in child:
             print(element.tag, element.attrib)
这是我打印出来的结果的一部分

<Listings>
  <Listing>
    <Location>
      <City>Amagansett</City>
      <State>NY</State>
      <Zip>11930</Zip>
      <Latitude>4.12</Latitude>
      <Longitude>2.13</Longitude>
      <DisplayAddress>No</DisplayAddress>
    </Location>
    <ListingDetails>
      <Status>For Rent</Status>
      <Price>120000</Price>
      <ListingUrl>http://www.co.com/listing.aspx?   Region=LI3&amp;ListingID=122</ListingUrl>
      <MlsId>122</MlsId>
      <DateListed>2011-06-10</DateListed>
      <NewDevelopment>N</NewDevelopment>
    </ListingDetails>
    <BasicDetails>
      <PropertyType>Other</PropertyType>
      <Description>Rental Registration #: the master suite has a lavish bath and its own terrace with small ocean views..</Description>
      <Bedrooms>5</Bedrooms>
      <Bathrooms>4</Bathrooms>
      <FullBathrooms>4</FullBathrooms>
      <HalfBathrooms>0</HalfBathrooms>
      <LivingArea>5775</LivingArea>
      <LotSize>0.8</LotSize>
    </BasicDetails>

  </Listing>
</Listings>

阿马甘塞特
纽约
11930
4.12
2.13
不
供出租
120000
http://www.co.com/listing.aspx?   地区=LI3&;ListingID=122
122
2011-06-10
N
其他
租房登记:主卧套房有一个豪华的浴室和自己的阳台,可以看到小海景。。
5.
4.
4.
0
5775
0.8
我想我明白了! 这是我用过的

import xml.etree.ElementTree       
res=[]
for child in root:
    r=[]
    for element in child:
        for element in element:
            new=element.text
            r.append(new)

    res.append(r) 
print (res)

尝试使用xmltodict——因为在我看来它更容易

 import xmltodict


 with open('file.xml',encoding="utf8") as datafile:

   doc = xmltodict.parse(datafile.read())

for row in doc['Listings']['Listing']['Location']:
 try:

        #City
       print(row['City'],'City')

    except Exception:
                   pass

我使用了Try-and-expect-exception,因为XML文件通常具有不同的结构,所以在尝试获取不存在的内容时可能会出错。

将代码或数据作为图片发布是不好的。无法将图片复制并粘贴到代码编辑器中。因此,要有人帮忙会困难得多,也就不太可能了。为了最大限度地利用网站,重要的是,这包括创建一个示例。我相信您需要
elem.tag
elem.text
当然,请稍候。谢谢你,我把照片移走了。pic不是代码,它只是我需要解析的xml文件的屏幕截图。