2012-10-25 62 views
1

鑑於此代碼:完全表示

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 

我想獲得:

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

我只是想知道的Python如何處理__repr__通話對象只是爲了獲得obj參數裏面顯示text屬性而不是空字典。

+0

你用什麼解析器?只是這樣我才能重現你的代碼。 –

+0

@MartijnPieters從xml.dom.minidom進口parseString :) – markcial

回答

1

只是經過一番google搜索終於找到了答案,只是爲了信息我會後回答這裏

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__ 

謝謝大家反正:)

+1

嘿,我剛剛發佈,你需要添加'__repr__'以及。 :-) –

+0

@MartijnPieters無論如何感謝:D – markcial