我正在尝试执行某种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)