python 2.7,xml,beautifulsoup4:只返回匹配的父标记

时间:2014-01-25 01:35:24

标签: python xml parsing beautifulsoup

我正在尝试解析一些XML,但遇到的问题是强制它只选择请求标记(如果它是父标记)。例如,我的部分XML是:

<Messages>
    <Message ChainCode="LI" HotelCode="5501" ConfirmationID="5501">
      <MessageContent>
        <OTA_HotelResNotifRQ TimeStamp="2014-01-24T21:02:43.9318703Z" Version="4" ResStatus="Book">
          <HotelReservations>
            <HotelReservation>
              <RoomStays>
                <RoomStay MarketCode="CC" SourceOfBusiness="CRS">
                  <RoomRates>
                    <RoomRate EffectiveDate="2014-02-04" ExpireDate="2014-02-06" RoomTypeCode="12112" NumberOfUnits="1" RatePlanCode="RAC">
                      <Rates>
                        <Rate EffectiveDate="2014-02-04" ExpireDate="2014-02-06" RateTimeUnit="Day" UnitMultiplier="3">
                          <Base AmountBeforeTax="749.25" CurrencyCode="USD" />
                          <Total AmountBeforeTax="749.25" CurrencyCode="USD" />
                        </Rate>
                      </Rates>
                    </RoomRate>
                  </RoomRates>
                  <Total AmountBeforeTax="2247.75" CurrencyCode="USD">
                    <Taxes Amount="0.00" />
                  </Total>
                </RoomStay>
              </RoomStays>
            </HotelReservation>
          </HotelReservations>
        </OTA_HotelResNotifRQ>
      </MessageContent>
    </Message>
  </Messages>

除了“Total”标签之外,我已经解析了我需要它的全部内容。

我想要获得的总标签是:

 <Total AmountBeforeTax="2247.75" CurrencyCode="USD">
     <Taxes Amount="0.00" />
 </Total>

发生了什么,是否正在返回RoomRates \ RoomRate \ Rates \ Rate的子级“Total”标记。我正在试图弄清楚如何指定它只返回RoomStays \ RoomStay \ Total标签。我现在拥有的是:

soup = bs(response, "xml")

messages = soup.find_all('Message')

for message in messages:
    hotel_code = message.get('HotelCode')

    reservations = message.find_all('HotelReservation')
    for reservation in reservations:
        uniqueid_id = reservation.UniqueID.get('ID')
        uniqueid_idcontext = reservation.UniqueID.get('ID_Context')

        roomstays = reservation.find_all('RoomStay')
        for roomstay in roomstays:

            total = roomstay.Total

有关如何指定我想要提取的确切标记的任何想法?如果有人想知道for循环,那是因为通常有多个“消息”,“酒店预订”,“房间住宿”等标签,但我已将它们删除只显示一个。有时候还有多个Rate \ Rates标签,所以我不能要求它给我第二个“Total”标签。

希望我已经解释过这个。

1 个答案:

答案 0 :(得分:1)

  

有时候还有多个Rate \ Rates标签,所以我不能要求它给我第二个“Total”标签。

为什么不迭代所有Total标签并跳过那些没有Taxes孩子的标签?

reservations = message.find_all('HotelReservation')
for reservation in reservations:
    totals = reservation.find_all('Total')
    for total in totals:
        if total.find('Taxes'):
             # do stuff
        else:
             # these aren't the totals you're looking for

如果您更希望消除那些没有子节点的那些,您可以执行以下任一操作:

if next(total.children, None):
    # it's a parent of something

if total.contents:
    # it's a parent of something

或者你可以use a function instead of a string as your filter

total = reservation.find(lambda node: node.name == 'Total' and node.contents)

或者您可以通过其他方式查找此标记:它是RoomStay的直接子项,而不仅仅是后代;它不是Rate的后代;它是Taxes下的最后一个RoomStay后代;所有这些都可以轻松完成。


话虽这么说,这似乎是XPath的完美工作,BeautifulSoup不支持,但ElementTreelxml做...