[英]For loop: Parsing XML by ElementTree Python3
I designed this simplified XML file that is very similar to the XML file I'll have to parse. 我设计了这个简化的XML文件,该文件与我必须解析的XML文件非常相似。 I'm trying to parse the text from the following nodes(Food, Date, ItemCondition, Amount) 我正在尝试从以下节点(食物,日期,ItemCondition,金额)解析文本
<?xml version="1.0"?>
<Region>
<District>
<Store>
<Department>
<Produce>
<Food>Apple</Food>
</Produce>
</Department>
<ProductInfo>
<BoxofFruit>
<Qualifiers>
<ItemCondition>New</ItemCondition>
</Qualifiers>
<Date>101214</Date>
<Price>
<LandedPrice>
<CurrencyCode>USD</CurrencyCode>
<Amount>19.99</Amount>
</LandedPrice>
</Price>
</BoxofFruit>
<BoxofFruit>
<Qualifiers>
<ItemCondition>New</ItemCondition>
</Qualifiers>
<Date>091114</Date>
<Price>
<LandedPrice>
<CurrencyCode>USD</CurrencyCode>
<Amount>21.99</Amount>
</LandedPrice>
</Price>
</BoxofFruit>
</ProductInfo>
</Store>
</District>
</Region>
For the life of me I cant seem to get the Food text. 对于我的一生,我似乎无法获得食物的文字。 Heres my current code that works as long as I dont include the Food portion. 只要我不包含“食物”部分,这就是我当前的代码有效。
Fruit = root.findall('.//BoxofFruit')
for Apple in Fruit:
Date = Apple.find('Date').text
Condition = Apple.find('Qualifiers/ItemCondition').text
Price = Apple.find('Price/LandedPrice/Amount').text
print(Date, Condition, Price)
Here's what I receive from my code: 这是我从代码中收到的信息:
101214 New 19.99
091114 New 21.99
And here is an example of what I would like to see: 这是我想看到的示例:
Apple 101214 New 19.99
Apple 091114 New 21.99
Ive been fumbling with this for days. 我已经摸索了好几天。 I would very much appreciate the help. 我非常感谢您的帮助。
Since Food
is not in BoxofFruit
, you have to fetch it beforehand. 由于Food
不在BoxofFruit
,因此您必须事先获取它。 For example: 例如:
fruit = root.find('.//Food').text
for Apple in root.findall('.//BoxofFruit')
Date = Apple.find('Date').text
Condition = Apple.find('Qualifiers/ItemCondition').text
Price = Apple.find('Price/LandedPrice/Amount').text
print(fruit, Date, Condition, Price)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.