python - python通过路径获取xml元素
问题描述
我尝试浏览一个大的 xml 文件,并收集一些数据。由于可以通过路径找到数据的位置,所以我使用了xpath,但没有结果。
有人可以建议我做错了什么吗?
xml 示例:
<?xml version="1.0" encoding="UTF-8"?>
<rootnode>
<subnode1>
</subnode1>
<subnode2>
</subnode2>
<subnode3>
<listnode>
<item id="1"><name>test name1</name></item>
<item id="2"><name>test name2</name></item>
<item id="3"><name>test name3</name></item>
</listnode>
</subnode3>
</rootnode>
编码:
import lxml.etree as ET
tree = ET.parse('temp/temp.xml')
subtree = tree.xpath('./rootnode/subnode3/listnode')
for next_item in subtree:
Id = next_item.attrib.get('id')
name = next_item.find('name').text
print('{:>20} - {:>20}'.format(name,Id))
解决方案
你很接近。
前任:
import lxml.etree as ET
tree = ET.parse('temp/temp.xml')
subtree = tree.xpath('/rootnode/subnode3/listnode')
for next_item in subtree:
for item in next_item.findall('item'):
Id = item.attrib.get('id')
name = item.find('name').text
print('{:>20} - {:>20}'.format(name,Id))
或者
subtree = tree.xpath('/rootnode/subnode3/listnode/item')
for item in subtree:
Id = item.attrib.get('id')
name = item.find('name').text
print('{:>20} - {:>20}'.format(name,Id))
输出:
test name1 - 1
test name2 - 2
test name3 - 3
推荐阅读
- python - ImportError:无法从“skimage.draw”导入名称“disk”
- java - 带有 ResponseEntity 类型的 spring 表达式
- c++ - 如何将 dd-mmm-yyyy 和 now() 转换为天数?
- c# - 检查数据表中是否存在字符串的子字符串
- javascript - 获取 HTML 并使用 rasterizehtml 在画布中生成图像 - 动态源图像
- java - 检测自定义适配器的变化,从视图模型 LiveData 更新列表视图
- java - 如何在 JavaFX TableView 中显示 Mysql 数据库的列标题?
- excel - 如何检索条件格式单元格的背景颜色?
- c# - 我可以在 ML.NET 中使用二进制分类来分类 2 类图像吗?
- java - 使用 `-XX:+PerfDisableSharedMem` JVM 标志是否有任何性能劣势?