Skip to content

Commit

Permalink
DOM and SAX module
Browse files Browse the repository at this point in the history
  • Loading branch information
artuguen28 committed Nov 3, 2021
1 parent 3cefa86 commit cc27f0c
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 0 deletions.
18 changes: 18 additions & 0 deletions XML_Processing/DOM_module.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import xml.dom.minidom
import os


domtree = xml.dom.minidom.parse("XML_Processing\group.xml")
group = domtree.documentElement

persons = group.getElementsByTagName("person")

for person in persons:
print("--- Persons ---")
if person.hasAttribute("id"):
print("ID: %s" % person.getAttribute("id"))

name = person.getElementsByTagName ("name")[0]
age = person.getElementsByTagName("age")[0]
weight = person.getElementsByTagName("weight")[0]
height = person.getElementsByTagName("height")[0]
38 changes: 38 additions & 0 deletions XML_Processing/SAX_module.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import xml.sax

class GroupHandler(xml.sax.ContentHandler):

def startElement(self, name, attrs):
self.current = name
if self.current == "person":
print("--- Person ---")
id = attrs["id"]
print("ID: %s" % id)

def endElement(self, name):
if self.current == "name":
print("Name: %s" % self.name)
elif self.current == "age":
print("Age: %s" % self.age)
elif self.current == "weight":
print("Weight: %s" % self.weight)
elif self.current == "height":
print("Height: %s" % self.height)
self.current = ""

def characters(self, content):
if self.current == "name":
self.name = content
elif self.current == "age":
self.age = content
elif self.current == "weight":
self.weight = content
elif self.current == "height":
self.height = content


handler = GroupHandler()
parser = xml.sax.make_parser()
parser.setContentHandler(handler)
parser.parse("XML_Processing\group.xml")

33 changes: 33 additions & 0 deletions XML_Processing/group.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?xml version='1.0'?> <!--Indicates the version of XML-->
<group>
<person id="1">
<name>Jonh Smith</name>
<age>20</age>
<weight>80</weight>
<height>188</height>
</person>
<person id="2">
<name>Mike Davis</name>
<age>45</age>
<weight>82</weight>
<height>185</height>
</person>
<person id="3">
<name>Anna Johnson</name>
<age>33</age>
<weight>67</weight>
<height>167</height>
</person>
<person id="4">
<name>Bob Smith</name>
<age>60</age>
<weight>70</weight>
<height>174</height>
</person>
<person id="5">
<name>Sarah Pitt</name>
<age>12</age>
<weight>50</weight>
<height>152</height>
</person>
</group>

0 comments on commit cc27f0c

Please sign in to comment.