我需要找到最喜欢的电影数量和
电影不是。在XML文档中,我无法阅读此行<movie favorite="False
以提供所需信息。
在互联网上找到了它,但没有用
import xml.etree.ElementTree as ET
count = len(xml.findall(".//*[context='False']"))
**the other method that I tried**
for e in xml.findall(".//sub[context]"):
if e.find("context").text in ('movie favorite', 'False'):
count += 1
print(count)
我的XML文档如下所示
<?xml version='1.0' encoding='utf8'?>
<collection>
<genre category="Action">
<decade years="1980s">
<movie favorite="True" title=" Indiana Jones: The raiders of the Lost Ark">
<format multiple="No">DVD</format>
<year>1981</year>
<rating>PG</rating>
<description>
'Archaeologist and adventurer Indiana Jones
is hired by the U.S. government to find the Ark of the
Covenant before the Nazis.'
</description>
</movie>
<movie favorite="True" title="THE KARATE KID">
<format multiple="Yes">DVD,Online</format>
<year>1984</year>
<rating>PG</rating>
<description>None provided.</description>
</movie>
<movie favorite="False" title="Back 2 the Future">
<format multiple="False">Blu-ray</format>
<year>1985</year>
<rating>PG</rating>
<description>Marty McFly</description>
</movie>
</decade>
有人可以指出我做错了吗?
答案 0 :(得分:1)
您正尝试在XML
文档中选择与给定XPath
表达式匹配的标签。 XPath
库支持的xml.etree
表达式在这里描述:https://docs.python.org/3/library/xml.etree.elementtree.html#elementtree-xpath。
看看文档,我得到了一个简单的XPath
表达式,它可以满足您的要求:选择movie
类型且具有属性值的根的所有子元素favorite
设置为False
。
from xml.etree import ElementTree as Et
et.fromstring(xml)
e.findall('.//movie[@favorite="False"]')
[<Element 'movie' at 0x000001F20A6C48B8>, ...]