Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8742555
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T11:31:27+00:00 2026-06-13T11:31:27+00:00

Given this code: class XmlObj(dict): def __init__(self,xml,*args,**kwargs): super(dict,self).__init__(*args,**kwargs) if xml.firstChild.nodeName == ‘#text’: self.__setattr__( ‘text’,

  • 0

Given this code:

class XmlObj(dict):
    def __init__(self,xml,*args,**kwargs):
        super(dict,self).__init__(*args,**kwargs)
        if xml.firstChild.nodeName == '#text':
            self.__setattr__( 'text', xml.firstChild.nodeValue )
            return
        else:
            for node in xml.childNodes:
                if self.has_key( node.nodeName ):
                    item = self.__getitem__(node.nodeName)
                    if type( item ) is not type( [] ):
                        item = [item]
                        item.append( XmlObj( node ))
                    self.__setitem__(node.nodeName, item )
                else:
                    self.__setitem__(node.nodeName, XmlObj(node) )

    def __str__(self):
        if hasattr(self,'text'):
            return self.__getattribute__('text')
        else:
            return "%s"%super(dict,self).__str__()

text = """<?xml version="1.0"?><response><success>true</success><message>Metric List</message><page>1</page><rpp>50</rpp><total>9</total><pages>1</pages></response>"""
obj = XmlObj( parseString( text ).documentElement )
print obj
print obj['rpp']

>>> {u'rpp': {}, u'success': {}, u'pages': {}, u'message': {}, u'total': {}, u'page': {}}
>>> 50

I’d like to get :

>>> {u'rpp': '50', u'success': True, u'pages': 4, u'message': 'Some message', u'total': 90, u'page': 1}

I just wonder how Python handles the __repr__ call of the objects just to get the obj parameters inside display the text attribute instead the empty dict.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T11:31:27+00:00Added an answer on June 13, 2026 at 11:31 am

    Just after some googling finally found the answer, just for informational sake i’ ll post the answer here

    http://effbot.org/pyfaq/how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order.htm

    class XmlObj(dict):
        def __init__(self,xml,*args,**kwargs):
            super(dict,self).__init__(*args,**kwargs)
            if xml.firstChild.nodeName == '#text':
                self.__setattr__( 'text', xml.firstChild.nodeValue )
                return
            else:
                for node in xml.childNodes:
                    if self.has_key( node.nodeName ):
                        item = self.__getitem__(node.nodeName)
                        if type( item ) is not type( [] ):
                            item = [item]
                            item.append( XmlObj( node ))
                        self.__setitem__(node.nodeName, item )
                    else:
                        self.__setitem__(node.nodeName, XmlObj(node) )
    
        def __repr__(self):
            if hasattr(self,'text'):
                return self.__getattribute__('text')
            else:
                result = ["%r: %r" % (key, self[key]) for key in sorted(self)]
                return "{" + ", ".join(result) + "}"
    
        __str__ = __repr__
    

    thanks everybody anyways 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This code: class testclass: def __init__(self,x,y): self.x = x self.y = y self.test() def
Suppose I have this code: class Num: def __init__(self,num): self.n = num def getn(self):
given this code: class Foo def bar return Bar.new end end class Bar ...
Given this code: public class Messager implements Runnable { public static void main(String[] args)
From this block of code: class MainHandler(webapp2.RequestHandler): def get(self): template_values = {given_sentence:'put a sentence
Given this sample code: #include <iostream> #include <stdexcept> class my_exception_t : std::exception { public:
given this code namespace GridTests { public class Grid<T> { IEnumerable<T> DataSource { get;
Given this code sample: complex.h : #ifndef COMPLEX_H #define COMPLEX_H #include <iostream> class Complex
Given this code public interface IRepository<T> { IQueryable<T> GetAll(); } and this public class
Given this Java code: class Account { private Integer number = 0; public synchronized

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.