如何读取 xml 并使用 lxml 从元素中获取文本

How to read xml and get text from an element using lxml

我对从 xml

获取信息有点困惑

我的xml

<?xml version="1.0" encoding="UTF-8"?>
<AirShoppingRS Version="16.2" xsi:schemaLocation="http://www.iata.org/IATA/EDIST AirShoppingRS.xsd"
    xmlns="http://www.iata.org/IATA/EDIST"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Document/>
    <Success/>
    <ShoppingResponseID>
        <ResponseID>2017-10-04T14:35:25.243504</ResponseID>
    </ShoppingResponseID>
    <OffersGroup>
        <AirlineOffers>
            <TotalOfferQuantity>297</TotalOfferQuantity>
            <Owner>SU</Owner>
            <AirlineOffer>
                <OfferID Owner="SU">OFFER5</OfferID>
                <TotalPrice>
                    <SimpleCurrencyPrice Code="RUB">36229</SimpleCurrencyPrice>
                </TotalPrice>
                <PricedOffer>
                    <OfferPrice OfferItemID="5">
                        <RequestedDate>
                            <PriceDetail>
                                <TotalAmount>
                                    <SimpleCurrencyPrice>36229</SimpleCurrencyPrice>
                                </TotalAmount>
                                <BaseAmount>33000</BaseAmount>
                                <Taxes>
                                    <Total Code="RUB">3229</Total>
                                </Taxes>
                            </PriceDetail>
                        </RequestedDate>
                        <FareDetail>
                            <FareComponent>
                                <SegmentReference>SEG_SVOLED_1</SegmentReference>
                                <FareBasis>
                                    <FareBasisCode>
                                        <Code>DFOR</Code>
                                    </FareBasisCode>
                                </FareBasis>
                            </FareComponent>
                        </FareDetail>
                    </OfferPrice>
                </PricedOffer>
            </AirlineOffer>
        </AirlineOffers>
    </OffersGroup>
</AirShoppingRS>

如何使用 lxml 库阅读它。我尝试了这个 root = etree.fromstring(xml.content),然后又尝试了 airline_offers = root.findall("AirlineOffer"),但一无所获。猜猜,我做错了什么。我在哪里犯错?我怎样才能获得一个元素,然后从中获得文本或属性?

更新:airline_offers = root.findall(".//AirlineOffer") returns 没什么

在根元素上声明了默认命名空间 (http://www.iata.org/IATA/EDIST)。这是使其工作的一种方法:

airline_offers = root.findall(".//{http://www.iata.org/IATA/EDIST}AirlineOffer")

也可以使用通配符:

airline_offers = root.findall(".//{*}AirlineOffer")

另一种方法是定义前缀:

NS = {"edist": "http://www.iata.org/IATA/EDIST"}
airline_offers = root.findall(".//edist:AirlineOffer", namespaces=NS)