python - 从python中的XML文件中提取所有属性和标签以及行号
问题描述
所以我有一个标签列表,我想检查 XML 文件中有多少这些标签,我想获取相应的行号,以便我可以标记这些行并在我的 UI 端显示它们。我去阅读了lxml的文档,但我不能很好地理解它,我仍然被困在这个问题上,我什至无法启动代码。
以此为例:
<domain type='kmc' id='007'>
<name>virtual bug</name>
<uuid>66523dfdf555dfd</uuid>
<os>
<type>hvm</type>
<boot>Windows</boot>
</os>
<memory unit='KiB'>524288</memory>
<currentMemory unit='KiB'>270336</currentMemory>
<vcpu placement='static'>10</vcpu>
假设我想搜索
['name','boot']
我想逐行处理它。我该怎么做呢 ?我对标签值感兴趣,例如<something>Value<something>
,我想知道所有<something>
的行号。谢谢
解决方案
我们无法为您编写算法来执行此任务,这不是 SO 的用途,但我们可以指导您如何实现它。
您可以使用 ElementTree 并逐行解析 XML,当您找到要查找的行时,您可以对其进行操作。
对于行号,我会创建一个从 0 开始的计数器,并在每次在 child 中获得新行时增加它
import xml.etree.ElementTree as ET
tree = ET.parse('myfile.xml')
root = tree.getroot()
counter = 0;
for child in root:
print(child.tag, child.attrib)
counter++
if child.tag == "name"
print(counter)
你可以在这里找到更多关于它的信息:
https://www.datacamp.com/community/tutorials/python-xml-elementtree
推荐阅读
- sql - 如何在 SQL 表中返回具有列条件的前行值?
- python - 使用 tkinter 绘制一个表格,其中单元格需要在单击时着色并通过代码检索选项
- python - 芹菜版本兼容性问题
- python - 如何使用用户名密码连接 coreNLP 服务器?
- polymer-3.x - 为什么没有 @apply 导入的样式 mixin
- python - 如何调整系统参数以使 numpy 的 load() 和 save() 实现 AWS HDD 卷的最大带宽?
- python - 根据另一列的值从一列中过滤选定的类别
- javascript - 如何从html表中的选择框中获取值
- nativescript - 使用 Nativescript 创建的图表不显示任何值(=空图表)
- jquery - 使用 J Query 动态更改图像链接