How can I convert XML into a Python object?

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

    It's worth looking at lxml.objectify.

    xml = """
    content contenbar me
    """ from lxml import objectify main = objectify.fromstring(xml) main.object1[0] # content main.object1[1] # contenbar main.object1[0].get("attr") # name main.test # me

    Or the other way around to build xml structures:

    item = objectify.Element("item")
    item.title = "Best of python"
    item.price = 17.98
    item.price.set("currency", "EUR")
    
    order = objectify.Element("order")
    order.append(item)
    order.item.quantity = 3
    order.price = sum(item.price * item.quantity for item in order.item)
    
    import lxml.etree
    print(lxml.etree.tostring(order, pretty_print=True))
    

    Output:

    
      
        Best of python
        17.98
        3
      
      53.94
    
    

提交回复
热议问题