python获取元素属性_使用Python从元素及其子元素获取所有属性

我正在尝试执行某种xml(现在使用xml.etree.ElementTree)到JSON(研究Python,在我真正的非关键任务中使用它)。XML示例:

我当前的任务是:对于所有具有名为“setup”的子节点的“input”节点,获取公共的(连接的)名称和id(例如上面的:name=”ASI:ASI输入1“和 id="0:1"), then get all attributes of both nodes - current and child, excepting name and id (for example above: numTs, description, tsSync, ...)

我有很多基于不同主体(xpath,if/for)的“google”代码示例root.childNodes,等等),现在我可以从父节点或子节点中提取属性(以不同的方式)),但我无法获得所有属性。。在

然后,我需要将解析后的数据打印成JSON格式,如下所示:

^{pr2}$

(JSON是人类可读的,对于任何有效的JSON都足够了。)

如何以优雅的python方式解决我的任务?(算法简洁,错误和异常处理正确?)。先谢谢你!在

UPD我的进度:ExportData = ET.fromstring(xml)

# First, create empty Output Dict by Template

# It will be implemented with needet data later

outData = { 'data': [] }

# Then I create 2 Dicts, for node & subnode, if subnode consists

# necessery pattern

# All further manipulations will bi done with this Dicts

for input in ExportData.findall('input'):

if input.find('tuningSetup') is not None:

inputParams = input.attrib

setupParams = input.find('tuningSetup').attrib

inputId = inputParams['id'] + ':' + setupParams['id']

inputName = inputParams['name'] + ':' + setupParams['name']

del inputParams['name'], inputParams['id'] #, inputParams['numTs']

del setupParams['name'], setupParams['id'] #, setupParams['numTs']

commonParams = dict(inputParams.items() + setupParams.items())

for param, value in commonParams.iteritems():

outData['data'].append({ '{#INPUTID}': inputId, '{#INPUTNAME}': inputName, '{#INPUTPARAM}': param}

)

# Finally, dumping data to json

print json.dumps(outData, sort_keys=True, indent=2)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值