Editing XML as a dictionary in python?

前端 未结 8 1192
深忆病人
深忆病人 2020-12-31 18:11

I\'m trying to generate customized xml files from a template xml file in python.

Conceptually, I want to read in the template xml, remove some elements, change some

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 18:18

    For easy manipulation of XML in python, I like the Beautiful Soup library. It works something like this:

    Sample XML File:

    
      leaf1
      leaf2
    
    

    Python code:

    from BeautifulSoup import BeautifulStoneSoup, Tag, NavigableString
    
    soup = BeautifulStoneSoup('config-template.xml') # get the parser for the xml file
    soup.contents[0].name
    # u'root'
    

    You can use the node names as methods:

    soup.root.contents[0].name
    # u'level1'
    

    It is also possible to use regexes:

    import re
    tags_starting_with_level = soup.findAll(re.compile('^level'))
    for tag in tags_starting_with_level: print tag.name
    # level1
    # level2
    

    Adding and inserting new nodes is pretty straightforward:

    # build and insert a new level with a new leaf
    level3 = Tag(soup, 'level3')
    level3.insert(0, NavigableString('leaf3')
    soup.root.insert(2, level3)
    
    print soup.prettify()
    # 
    #  
    #   leaf1
    #  
    #  
    #   leaf2
    #  
    #  
    #   leaf3
    #  
    # 
    

提交回复
热议问题