def _xml_node_to_dict(node, repeats=[]):
assert isinstance(node, minidom.Node)
if len(node.childNodes) == 0:
# there's no data for this leaf node
return None
elif len(node.childNodes) == 1 and \
node.childNodes[0].nodeType == node.TEXT_NODE:
# there is data for this leaf node
return {node.nodeName: node.childNodes[0].nodeValue}
else:
# this is an internal node
value = {}
for child in node.childNodes:
# handle CDATA text section
if child.nodeType == child.CDATA_SECTION_NODE:
return {child.parentNode.nodeName: child.nodeValue}
d = _xml_node_to_dict(child, repeats)
if d is None:
continue
child_name = child.nodeName
child_xpath = xpath_from_xml_node(child)
assert d.keys() == [child_name]
node_type = dict
# check if name is in list of repeats and make it a list if so
if child_xpath in repeats:
node_type = list
if node_type == dict:
if child_name not in value:
value[child_name] = d[child_name]
else:
raise InstanceMultipleNodeError(
_(u"Multiple nodes with the same name '%s'"
u" while not a repeat" % child_name))
else:
if child_name not in value:
value[child_name] = [d[child_name]]
else:
value[child_name].append(d[child_name])
if value == {}:
return None
else:
return {node.nodeName: value}
xform_instance_parser.py 文件源码
python
阅读 24
收藏 0
点赞 0
评论 0
评论列表
文章目录