.text使用XML.etree.ElementTree从XML文档输出

2024-10-03 11:22:02 发布

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

我试图解析XML文档,以便只获取标记内的文本,但当我测试打印节点时,它只显示方括号,这意味着我的命令print(rede.text)返回“AttributeError:‘list’对象没有属性‘text’”。为什么XML内容存储为列表对象,以及如何访问标记中的文本

import os
from xml.etree import ElementTree
file_name = '19008-data.xml'
full_file = os.path.abspath(os.path.join('WP19_Protokolle_2018-2020',file_name))
dom = ElementTree.parse(full_file)
redner = dom.findall('rede')
print(redner)

输出:[]

import os
from xml.etree import ElementTree
file_name = '19008-data.xml'
full_file = os.path.abspath(os.path.join('WP19_Protokolle_2018-2020',file_name))
dom = ElementTree.parse(full_file)
redner = dom.findall('rede')
print(redner.text)

AttributeError:“列表”对象没有属性“文本”

extract from XML-document


Tags: path对象textname文本importosxml
2条回答

Why is the XML-content stored as a list object and how I can access the text inside the tag?

XML内容不存储为列表。当我们查看^{}方法的文档时,我们看到它:

Returns a list containing all matching elements in document order.

在您的特定情况下,该方法找不到任何内容,因此返回了一个空列表。显然,您无法在不存在的元素中找到文本

在正式文件{a1}中,我们可以看到以下解释:

*Element.findall()*只查找带有标记的元素,这些元素是当前元素的直接子元素。Element.find()查找带有特定标记的第一个子元素,Element.text访问元素的文本内容。get()访问元素的属性:

for country in root.findall('country'):
    rank = country.find('rank').text
    name = country.get('name')
    print(name, rank)

相关问题 更多 >