gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:42 25 4
gpt4 key购买 nike

我对从 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") 也不返回任何内容

最佳答案

默认命名空间 (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)

关于python - 如何使用 lxml 读取 xml 并从元素中获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46566213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com