首页 > 解决方案 > 无法弄清楚如何从 xml 文件中填充字典

问题描述

我是python的新手。我在 2.7 中工作,我正在尝试解析 XML 文件以填充字典并跟踪变量名的使用次数(名称会改变,因此字典),它还需要跳过数字和变量名中的冒号。我知道我需要将它作为一个元素拉出来,以便我可以操纵它,但我不确定如何操作。请帮忙。这是我与一段 XML 代码一起回溯的内容。

import xml.etree.ElementTree as ET

tree = ET.parse(sample.xml)
root = tree.getroot()

d = {}

for iec-source in root:

    variable_code = variable.find('variable-name')

if variable_code.text == #varibale is in dictionary add count

else #add to dictionary and add count

xml图片

标签: pythonxml

解决方案


因此,首先,您将要提取所有 variable_name 节点。该.find方法将返回与指定 XPATH 匹配的第一个节点。该方法将返回一个包含所有匹配节点.findall的数组。接下来,您将要处理文本。如果您知道所有变量名称都有冒号,则可以在字符串上使用。最后,您可以使用来检查密钥是否存在。.split()if key in dict.keys()

import xml.etree.ElementTree as ET

tree = ET.parse("sample.xml")
root = tree.getroot()

dict = {}

# Loop through all nodes with tag <variable_name>
for variable_name in root.findall(".//variable_name"):

    text = variable_name.text    # Get the raw text from the xml

    variable = text.split(":")[1]    # Splits the text into an array
                                     # ["#","VARIABLE"]
                                     # keep the second element

    if variable in dict.keys():
        dict[variable] += 1    # Increment the count for that variable
    else:
        dict[variable] = 1     # Add the new variable to dict, initialize to 1

推荐阅读