首页 > 解决方案 > 从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>的行号。谢谢

标签: pythonjsonpython-3.xxml

解决方案


我们无法为您编写算法来执行此任务,这不是 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


推荐阅读