如何使用子元素遍历子元素

How to iterate through child element using child element

我需要在默认词典中输入 XML 文件的元素。 使用第一个子元素作为我的键,其他 2 个值将在列表中。

我试过将元素放在单独的列表中,然后将它们配对,但仍然没有成功。

下面是XML结构

<lines>
    <line>
        <lineName>'Line 1'</lineName>
        <lineCode>'5501'</lineCode>
        <machineName>'Line_1'</machineName>
    </line>
    <line>
        <lineName>'Line 2'</lineName>
        <lineCode>'5502'</lineCode>
        <machineName>'Line_2'</machineName>
    </line>
</lines>

这是我检索元素的方式

item = myxmlcfg.getElementsByTagName('lineName')

item 是一个包含 2 个元素的列表

item['Line 1', 'Line 2']

lineCode 和 machineName 元素也会发生同样的情况

所以我需要一个输出为这个的默认字典

lines {'Line 1': ['5501', 'Line_1'], 'Line 2':['5502', 'Line_2']}

其中 KeylineName 标签,value 是一个包含 2 个元素的列表,其值为 lineCodemachineName.

你能建议我一种迭代 xml 元素以获得上述输出的方法吗? 任何帮助将不胜感激。 谢谢

我没有任何使用 minidom 的经验,但是使用 ElementTree 这是一项微不足道的任务:

from xml.etree import ElementTree as ET
from xml.etree.ElementTree import ElementTree

if __name__ == '__main__':

    xml_raw = '''
    <lines>
        <line>
            <lineName>'Line 1'</lineName>
            <lineCode>'5501'</lineCode>
            <machineName>'Line_1'</machineName>
        </line>
        <line>
            <lineName>'Line 2'</lineName>
            <lineCode>'5502'</lineCode>
            <machineName>'Line_2'</machineName>
        </line>
    </lines>
    '''

    root: ElementTree = ET.fromstring(xml_raw)
    lines = {}
    for line in root.findall('line'):
        name = line.findtext('lineName').strip("'")
        code = line.findtext('lineCode').strip("'")
        machine = line.findtext('machineName').strip("'")
        lines[name] = [code, machine]
    print(lines)

输出:

{'Line 1': ['5501', 'Line_1'], 'Line 2': ['5502', 'Line_2']}

使用 lxml.etreeElement.itersiblings():

from lxml import etree

root=etree.fromstring(xml)
item=root.findall(f'.//lineName')
lines={i.text.strip("'"): [s.text.strip("'") for s in i.itersiblings()] for i in item}

输出:

{'Line 1': ['5501', 'Line_1'], 'Line 2': ['5502', 'Line_2']}

这里

import xml.etree.ElementTree as ET

xml = '''<lines>
    <line>
        <lineName>'Line 1'</lineName>
        <lineCode>'5501'</lineCode>
        <machineName>'Line_1'</machineName>
    </line>
    <line>
        <lineName>'Line 2'</lineName>
        <lineCode>'5502'</lineCode>
        <machineName>'Line_2'</machineName>
    </line>
</lines>'''

root = ET.fromstring(xml)
lines = root.findall('.//line')


  data = {
line.find('lineName').text.strip("'"): [line.find('lineCode').text.strip("'"), line.find('machineName').text.strip("'")]
for line in lines}

打印(数据)

输出

{'Line 1': ['5501', 'Line_1'], 'Line 2': ['5502', 'Line_2']}