我对从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")
也不返回任何内容
答案 0 :(得分:1)
在根元素上声明了默认名称空间(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)