python - XML 属性为空
问题描述
我正在从文件中将 xml 对象读入 Windows 10 上的 Python 3.6。这是xml的示例:
<?xml version="1.0"?>
<rss version="2.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<item>
<BurnLocation>@ 32 40 52.99 @ 80 57 33.00</BurnLocation>
<geo:lat>32.681389</geo:lat>
<geo:long>-80.959167</geo:long>
<County>Jasper</County>
<BurnType>PD</BurnType>
<BurnTypeDescription>PILED DEBRIS</BurnTypeDescription>
<Acres>2</Acres>
</item>
<item>
<BurnLocation>@ 33 29 34.26 @ 81 15 52.89</BurnLocation>
<geo:lat>33.492851</geo:lat>
<geo:long>-81.264694</geo:long>
<County>Orangebrg</County>
<BurnType>PD</BurnType>
<BurnTypeDescription>PILED DEBRIS</BurnTypeDescription>
<Acres>1</Acres>
</item>
</channel>
</rss>
这是我的代码的一个版本:
import os
import xml.etree.ElementTree as ET
local_filename = os.path.join('C:\\Temp\\test\\', filename)
tree = ET.parse(local_filename)
root = tree.getroot()
for child in root:
for next1 in child:
for next2 in next1:
print(next2.tag,next2.attrib)
我遇到的问题是我似乎无法隔离子标签的属性,它们作为空字典出现。这是一个结果示例:
BurnLocation {}
{http://www.w3.org/2003/01/geo/wgs84_pos#}lat {}
{http://www.w3.org/2003/01/geo/wgs84_pos#}long {}
County {}
BurnType {}
BurnTypeDescription {}
Acres {}
BurnLocation {}
{http://www.w3.org/2003/01/geo/wgs84_pos#}lat {}
{http://www.w3.org/2003/01/geo/wgs84_pos#}long {}
County {}
BurnType {}
BurnTypeDescription {}
Acres {}
我正在尝试打印标签中的项目(即 Jasper),我做错了什么?
解决方案
您在这里想要的是text
每个元素的内容,而不是它们的属性。
应该这样做(对于固定文件名稍微简化):
import xml.etree.ElementTree as ET
tree = ET.parse('sample.xml')
root = tree.getroot()
for child in root:
for next1 in child:
for next2 in next1:
print ('{} = "{}"'.format(next2.tag,next2.text))
print ()
但是,我会通过以下方式简化它:
- 一次定位所有
<item>
元素,并且 - 然后循环其子元素。
因此
import xml.etree.ElementTree as ET
tree = ET.parse('sample.xml')
for item in tree.findall('*/item'):
for elem in list(item):
print ('{} = "{}"'.format(elem.tag,elem.text))
print ()
推荐阅读
- python - 变长参数函数
- javascript - 结合 withLatestFrom 向 Observable 添加延迟“防止”订阅
- javascript - 如何修复显示空白的博客顶部菜单栏?
- php - 我需要有关使用 PHP 从一周数中获取天数列表的帮助
- mysql - 为什么使用 `HAVING` 而不是 `WHERE` 不会给出相同的结果?
- rstudio - 在 html kitted R markdown Presentation 中嵌入字体
- android - 如何检查我的小部件屏幕何时像 Android 中的 onResume 一样在颤动中可见
- php - 如何计算用户在一个月 laravel 中添加的帖子?
- go - 如何安全地将布尔字段添加到 gRPC 服务器结构?
- charts - 水平轴标签未使用 100% 宽度(谷歌图表)