Commits

Matt Bone committed 1f33eb3

works with xml expression tree

  • Participants
  • Parent commits 78abe3e

Comments (0)

Files changed (2)

File lecture/expression.xml

 <expression>
   <subtract>
     <add>
-      <integer value="1"/>
+      <integer value="3"/>
       <multiply>
         <integer value="2"/>
         <integer value="20"/>
       </multiply>
     </add>
+    <integer value="1"/>
   </subtract>
 </expression>

File lecture/expression_parser.py

 import json
 import unittest
+from xml.etree import ElementTree
 
 class IntegerNode(object):
     def __init__(self, value):
 
 
 def parse_xml(blob):
-    pass
+    element_tree = ElementTree.fromstring(blob)
+    def _parse_xml(node):
+        if node.tag == "expression":
+            return _parse_xml(node.getchildren()[0])
+        elif node.tag == "add":
+            return AdditionNode([_parse_xml(child) for child in node.getchildren()])
+        elif node.tag == "subtract":
+            return SubtractionNode([_parse_xml(child) for child in node.getchildren()])
+        elif node.tag == "multiply":
+            return MultiplicationNode([_parse_xml(child) for child in node.getchildren()])
+        elif node.tag == "integer":
+            return IntegerNode(int(node.attrib["value"]))
+    return _parse_xml(element_tree)
 
 
 class ExpressionParserTest(unittest.TestCase):
         tree = parse_json(json_blob)
         self.assertEquals(42, tree.value)
 
+    def test_parse_xml(self):
+        xml_blob = open("expression.xml").read()
+        tree = parse_xml(xml_blob)
+        self.assertEquals(42, tree.value)
+
 if __name__ == "__main__":
     unittest.main()