用python解析xml文件获取父元素

2024-06-16 17:53:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下名为test.xml的xml文件:

<?xml version="1.0"?>
<schematic>
    <receipe id="1" name="" count="4">
        <wire source="24:TbPowerSupplyChassisConnectionPoint_1"/>
        <wire source="25:TbPowerSupplyChassisConnectionPoint_1"/>
        <wire source="26:TbPowerSupplyChassisConnectionPoint_1"/>
    </receipe>
    <receipe id="2" name="" count="3">
        <wire source="14:TbPowerSupplyChassisConnectionPoint_1"/>
        <wire source="15:TbPowerSupplyChassisConnectionPoint_1"/>
        <wire source="16:TbPowerSupplyChassisConnectionPoint_1"/>
    </receipe>
</schematic>

我正在用Python中的ElementTree解析文件,要求使用ElementTreefindall()方法从整个xml文件中获取所有“wire”元素。当我有wire元素的列表时,我需要获取一些wire元素的parent recipe标记。Python代码示例如下:

import xml.etree.ElementTree as ET

print "parse"
xml = ET.parse("test.xml")
for wire in xml.findall('.//wire'):
    print wire.get('source').split(':')[0]
    //Need to get parent receipe element here from wire

我到处寻找,找到了一些方法,但似乎没有什么好的工作。还跟踪了一些堆栈溢出帖子,但也没有起作用。任何帮助都将不胜感激。下面是我尝试使用的一些方法,但没有一种有效。你知道吗

wire.iterancestors()
wire.get('parent')
wire.getroot()
wire.find('..')

Tags: 文件方法nametestid元素sourceget
1条回答
网友
1楼 · 发布于 2024-06-16 17:53:47

我不知道这有用吗?你知道吗

In [103]: from myparser import parse

In [104]:

In [104]: payload = """<?xml version="1.0"?>
     ...: <schematic>
     ...:     <receipe id="1" name="" count="4">
     ...:         <wire source="24:TbPowerSupplyChassisConnectionPoint_1"/>
     ...:         <wire source="25:TbPowerSupplyChassisConnectionPoint_1"/>
     ...:         <wire source="26:TbPowerSupplyChassisConnectionPoint_1"/>
     ...:     </receipe>
     ...:     <receipe id="2" name="" count="3">
     ...:         <wire source="14:TbPowerSupplyChassisConnectionPoint_1"/>
     ...:         <wire source="15:TbPowerSupplyChassisConnectionPoint_1"/>
     ...:         <wire source="16:TbPowerSupplyChassisConnectionPoint_1"/>
     ...:     </receipe>
     ...: </schematic>"""

In [105]: result = parse(payload)

In [108]: result.attr_mapping
Out[108]:
{'schematic.receipe.0.wire.0': {u'source': u'24:TbPowerSupplyChassisConnectionPoint_1'},
 'schematic.receipe.0.wire.1': {u'source': u'25:TbPowerSupplyChassisConnectionPoint_1'},
 'schematic.receipe.0.wire.2': {u'source': u'26:TbPowerSupplyChassisConnectionPoint_1'},
 'schematic.receipe.1.wire.0': {u'source': u'14:TbPowerSupplyChassisConnectionPoint_1'},
 'schematic.receipe.1.wire.1': {u'source': u'15:TbPowerSupplyChassisConnectionPoint_1'},
 'schematic.receipe.1.wire.2': {u'source': u'16:TbPowerSupplyChassisConnectionPoint_1'}}

相关问题 更多 >