我有深层嵌套的xml标签Movie,我想直接使用xpath访问。

<?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>
</decade>
</genre>
</collection>
</xml>


如何访问movie标记及其属性?
我尝试使用

root  = etee.tostring(above_xml)
print root.xpath("movie")
[]


但我什么也没得到。

最佳答案

我不确定这是您要寻找的内容,但是请尝试以下操作:

tree = lxml.etree.fromstring(xml_above, parser=lxml.etree.HTMLParser())
film =  tree.xpath("//movie/*/text()")
for i in film:
    print(i)


输出:

DVD
1981
PG

            'Archaeologist and adventurer Indiana Jones
            is hired by the U.S. government to find the Ark of the
            Covenant before the Nazis.'

关于python - 如何使用xml中的xpath访问其他标签内部的标签?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55901637/

10-12 12:36
查看更多