【问题标题】:How to parse multi-level XML file with python如何用python解析多级XML文件
【发布时间】:2018-08-25 00:28:03
【问题描述】:

我有一个需要用 python 解析的多级 XML 文件,我有 xml 或 lxml。我该如何解析?我找不到任何有用的解决方案。请帮助我,非常感谢!理想情况下,我想解析 XML 文件并转换为 Python DataFrame。 这个 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>

【问题讨论】:

  • 将代码或数据作为图片发布是不好的。无法将图片复制并粘贴到代码编辑器中。因此,有人提供帮助将更加困难,因此不太可能。为了充分利用该站点,ask good questions 很重要,其中包括创建一个 Minimal, Complete, and Verifiable 示例。
  • 我相信你想要elem.tagelem.text
  • 当然,等等。谢谢。
  • 我删除了图片。图片不是代码,只是我需要解析的xml文件的截图。

标签: python xml parsing lxml


【解决方案1】:

我想我明白了! 这是我用的。

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)

【讨论】:

    【解决方案2】:

    尝试使用 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 异常 - 因为 XML 文件通常具有不同的结构,因此在尝试获取不存在的内容时可能会出错。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-30
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      • 1970-01-01
      • 2020-08-04
      相关资源
      最近更新 更多