使用xml时获取正确值时出现问题。

2024-09-30 10:39:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从xml文件导出所有电影标题,但似乎无法获取标题。xml看起来像:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<videodb>
    <version>1</version>
    <movie>
        <title>2 Guns</title>
        <originaltitle>2 Guns</originaltitle>
        <ratings>
            <rating name="themoviedb" max="10" default="true">
                <value>6.500000</value>
                <votes>1776</votes>
            </rating>
        </ratings>

我已经看到了很多xml有value="title"的值的示例,但是找不到一个在没有value="title"时有效的指导示例

到目前为止,我的代码是:

#Import required library
import xml.etree.cElementTree as ET
root = ET.parse('D:\\temp\\videodb.xml').getroot()

for type_text in root.findall('movie/title'):
    value = type_text.get ('text')
    print(value)

Tags: text标题示例titlevalueversionxmlmovie
2条回答

XML文件:

<?xml version="1.0" encoding="utf-8"?>
<videodb>
    <version>1</version>
    <movie>
        <title>2 Guns</title>
        <originaltitle>2 Guns</originaltitle>
        <ratings>
            <rating name="themoviedb" max="10" default="true">
                <value>6.500000</value>
                <votes>1776</votes>
            </rating>
        </ratings>
    </movie>
    <movie>
        <title>Top Gun</title>
        <originaltitle>Top Gun</originaltitle>
        <ratings>
            <rating name="themoviedb" max="10" default="true">
                <value>7.500000</value>
                <votes>1566</votes>
            </rating>
        </ratings>
    </movie>
    <movie>
        <title>Inception</title>
        <originaltitle>Inceptions</originaltitle>
        <ratings>
            <rating name="themoviedb" max="10" default="true">
                <value>9.500000</value>
                <votes>177346</votes>
            </rating>
        </ratings>
    </movie>
</videodb>

代码:

import xml.etree.ElementTree as ET
tree = ET.parse('E:\Python\DataFiles\movies.xml') # replace with your path
root = tree.getroot()
for aMovie in root.iter('movie'):
    print(aMovie.find('title').text)

输出:

2 Guns
Top Gun
Inception

尝试替换:

value = type_text.get ('text')

value = type_text.text

xml.etree使用^{}检索内容元素属性

您正在查找元素文本;见Element.text

例如,考虑到这种人为设计的XML:

<element some_attribute="Some Attribute">Some Text</element>

.get('some_attribute')将返回Some Attribute,而.text将返回Some Text

相关问题 更多 >

    热门问题