How can I convert XML into a Python object?

后端 未结 7 1804
醉话见心
醉话见心 2020-12-02 10:46

I need to load an XML file and convert the contents into an object-oriented Python structure. I want to take this:

7条回答
  •  心在旅途
    2020-12-02 11:13

    #@Stephen: 
    #"can't hardcode the element names, so I need to collect them 
    #at parse and use them somehow as the object names."
    
    #I don't think thats possible. Instead you can do this. 
    #this will help you getting any object with a required name.
    
    import BeautifulSoup
    
    
    class Coll(object):
        """A class which can hold your Foo clas objects 
        and retrieve them easily when you want
        abstracting the storage and retrieval logic
        """
        def __init__(self):
            self.foos={}        
    
        def add(self, fooobj):
            self.foos[fooobj.name]=fooobj
    
        def get(self, name):
            return self.foos[name]
    
    class Foo(object):
        """The required class
        """
        def __init__(self, name, attr1=None, attr2=None):
            self.name=name
            self.attr1=attr1
            self.attr2=attr2
    
    s="""
    value1 value2 value3 value4
    """

    #

    soup=BeautifulSoup.BeautifulSoup(s)
    
    
    bars=Coll()
    for each in soup.findAll('object'):
        bar=Foo(each['name'])
        attrs=each.findAll('attr')
        for attr in attrs:
            setattr(bar, attr['name'], attr.renderContents())
        bars.add(bar)
    
    
    #retrieve objects by name
    print bars.get('somename').__dict__
    
    print '\n\n', bars.get('someothername').__dict__
    

    output

    {'attr2': 'value2', 'name': u'somename', 'attr1': 'value1'}
    
    
    {'attr2': 'value4', 'name': u'someothername', 'attr1': 'value3'}
    

提交回复
热议问题