from xml.dom.minidom import parseString dom = parseString("<expression><operation type=\"+\"><operand>2</operand><operand><operation type=\"*\"><operand>3</operand><operand>4</operand></operation></operand></operation></expression>") def calc_xml_expr (expr_node) : if expr_node.nodeName == "operation" : res = 0 op_code = expr_node.getAttribute("type") oprndElems = expr_node.getElementsByTagName("operand") if op_code == "+" : return calc_xml_expr(oprndElems[0]) + calc_xml_expr(oprndElems[1]) elif op_code == "*" : return calc_xml_expr(oprndElems[0]) * calc_xml_expr(oprndElems[1]) if expr_node.nodeName == "operand" : child_node = expr_node.childNodes[0] if child_node.nodeType == child_node.TEXT_NODE : return int(child_node.nodeValue) else: return calc_xml_expr(child_node) print calc_xml_expr(dom.getElementsByTagName("expression")[0].getElementsByTagName("operation")[0])
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question