Get attributes value by sax python

Viewed 14

I have a Nested chunk of XML that I want to get attributes of XML via SAX custom handler, the XML is below, in this case, I want to get images elements attributes value (Id and URL):

    <people id="1">
       <firstname>john</firstname>
       <lastname> smith</lastname>
       <profile>
        <image id="1" url="http://any.com/img/profile.jpg" />
        <image id="2" url="http://any.com/img/banner.jpg" />
       </profile>
     </people>

and the code is like :

import xml.sax 

class PeopleHandler(xml.sax.ContentHandler):
      
    def startElement(self, name, attrs):
        self.current = name
       
        if name == "people":
            print(f"-- People {attrs['id']} --")        
    
    def characters(self, name,content):
        if self.current == "people":
            self.people = content
        if self.current == "firstname":
            self.firstname = content
        if self.current == "lastname":
            self.lastname = content
        if self.current == "images":
            self.images = content
        
       


    def endElement(self, item):
        if self.current == "firstname":
            print(f"First name: {self.ferstname}")
        elif self.current == "lastname":
            print(f"Last name: {self.lastname}")
        elif self.current == "images":
            print(f"Images: {self.images}")
        self.current = ""
        


handler = PeopleHandler()
parser = xml.sax.make_parser()
parser.setContentHandler(handler)
parser.parse('main.xml')
0 Answers
Related