XML 文档的 .text 输出 xml.etree.ElementTree
.text output from XML document with xml.etree.ElementTree
我正在尝试解析 XML 文档,以便只获取标签内的文本,但是当我测试打印节点时,它只显示方括号,这意味着我的命令打印(rede.text) returns “AttributeError: 'list' 对象没有属性 'text'”。为什么 XML-content 存储为列表对象以及如何访问标签内的文本?
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: 'list' 对象没有属性 'text'
在官方文档中https://docs.python.org/3/library/xml.etree.elementtree.html我们可以看到接下来的解释:
*Element.findall()* 仅查找具有标记且是当前元素的直接子元素的元素。 Element.find() 找到第一个带有特定标签的子元素,Element.text 访问元素的文本内容。 Element.get() 访问元素的属性:
for country in root.findall('country'):
rank = country.find('rank').text
name = country.get('name')
print(name, rank)
Why is the XML-content stored as a list object and how I can access the text inside the tag?
XML 内容未存储为列表。当我们查看 Element.findall()
方法的文档时,我们看到它:
Returns a list containing all matching elements in document order.
在您的特定情况下,该方法未找到任何内容,因此返回了一个空列表。显然,您无法在不存在的元素中找到文本。
我正在尝试解析 XML 文档,以便只获取标签内的文本,但是当我测试打印节点时,它只显示方括号,这意味着我的命令打印(rede.text) returns “AttributeError: 'list' 对象没有属性 'text'”。为什么 XML-content 存储为列表对象以及如何访问标签内的文本?
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: 'list' 对象没有属性 'text'
在官方文档中https://docs.python.org/3/library/xml.etree.elementtree.html我们可以看到接下来的解释:
*Element.findall()* 仅查找具有标记且是当前元素的直接子元素的元素。 Element.find() 找到第一个带有特定标签的子元素,Element.text 访问元素的文本内容。 Element.get() 访问元素的属性:
for country in root.findall('country'):
rank = country.find('rank').text
name = country.get('name')
print(name, rank)
Why is the XML-content stored as a list object and how I can access the text inside the tag?
XML 内容未存储为列表。当我们查看 Element.findall()
方法的文档时,我们看到它:
Returns a list containing all matching elements in document order.
在您的特定情况下,该方法未找到任何内容,因此返回了一个空列表。显然,您无法在不存在的元素中找到文本。