Creating a simple XML file using python

前端 未结 6 971
野性不改
野性不改 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:25

    The lxml library includes a very convenient syntax for XML generation, called the E-factory. Here's how I'd make the example you give:

    #!/usr/bin/python
    import lxml.etree
    import lxml.builder    
    
    E = lxml.builder.ElementMaker()
    ROOT = E.root
    DOC = E.doc
    FIELD1 = E.field1
    FIELD2 = E.field2
    
    the_doc = ROOT(
            DOC(
                FIELD1('some value1', name='blah'),
                FIELD2('some value2', name='asdfasd'),
                )   
            )   
    
    print lxml.etree.tostring(the_doc, pretty_print=True)
    

    Output:

    
      
        some value1
        some value2
      
    
    

    It also supports adding to an already-made node, e.g. after the above you could say

    the_doc.append(FIELD2('another value again', name='hithere'))
    

提交回复
热议问题