How can I convert XML into a Python object?

后端 未结 7 1740
醉话见心
醉话见心 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:19

    I've been recommending this more than once today, but try Beautiful Soup (easy_install BeautifulSoup).

    from BeautifulSoup import BeautifulSoup
    
    xml = """
    <main>
        <object attr="name">content</object>
    </main>
    """
    
    soup = BeautifulSoup(xml)
    # look in the main node for object's with attr=name, optionally look up attrs with regex
    my_objects = soup.main.findAll("object", attrs={'attr':'name'})
    for my_object in my_objects:
        # this will print a list of the contents of the tag
        print my_object.contents
        # if only text is inside the tag you can use this
        # print tag.string
    
    0 讨论(0)
提交回复
热议问题