Creating a simple XML file using python

前端 未结 6 978
野性不改
野性不改 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条回答
  •  盖世英雄少女心
    2020-11-22 15:22

    Yattag http://www.yattag.org/ or https://github.com/leforestier/yattag provides an interesting API to create such XML document (and also HTML documents).

    It's using context manager and with keyword.

    from yattag import Doc, indent
    
    doc, tag, text = Doc().tagtext()
    
    with tag('root'):
        with tag('doc'):
            with tag('field1', name='blah'):
                text('some value1')
            with tag('field2', name='asdfasd'):
                text('some value2')
    
    result = indent(
        doc.getvalue(),
        indentation = ' '*4,
        newline = '\r\n'
    )
    
    print(result)
    

    so you will get:

    
        
            some value1
            some value2
        
    
    

提交回复
热议问题