Creating a simple XML file using python

前端 未结 6 979
野性不改
野性不改 2020-11-22 14:55

What are my options if I want to create a simple XML file in python? (library wise)

The xml I want looks like:


 
     

        
6条回答
  •  猫巷女王i
    2020-11-22 15:43

    For such a simple XML structure, you may not want to involve a full blown XML module. Consider a string template for the simplest structures, or Jinja for something a little more complex. Jinja can handle looping over a list of data to produce the inner xml of your document list. That is a bit trickier with raw python string templates

    For a Jinja example, see my answer to a similar question.

    Here is an example of generating your xml with string templates.

    import string
    from xml.sax.saxutils import escape
    
    inner_template = string.Template('    ${value}')
    
    outer_template = string.Template("""
     
    ${document_list}
     
    
     """)
    
    data = [
        (1, 'foo', 'The value for the foo document'),
        (2, 'bar', 'The  for the  document'),
    ]
    
    inner_contents = [inner_template.substitute(id=id, name=name, value=escape(value)) for (id, name, value) in data]
    result = outer_template.substitute(document_list='\n'.join(inner_contents))
    print result
    

    Output:

    
     
        The value for the foo document
        The <value> for the <bar> document
     
    
    

    The downer of the template approach is that you won't get escaping of < and > for free. I danced around that problem by pulling in a util from xml.sax

提交回复
热议问题