【问题标题】:Is there any way or any framework in python to create an object model from a xml?python中是否有任何方法或任何框架可以从xml创建对象模型?
【发布时间】:2012-07-04 17:43:45
【问题描述】:

例如我的 xml 文件包含:

<layout name="layout1">
    <grid>
        <row>
            <cell colSpan="1" name="cell1"/>
        </row>
        <row>
            <cell name="cell2" flow="horizontal"/>
        </row>
    </grid>
</layout>

我想从 xml 中检索一个对象 例如返回的对象结构是这样的

class layout(object):
     def __init__(self):
         self.grid=None
class grid(object):
     def __init__(self):
         self.rows=[]
class row(object):
     def __init__(self):
         self.cels=[]

【问题讨论】:

    标签: python xml data-modeling objectify


    【解决方案1】:

    我找到了答案 我在 lxml 包中使用了 objectify

    这是一个示例代码:

    from lxml import objectify
    
    root = objectify.fromstring("""
     <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
       <a attr1="foo" attr2="bar">1</a>
       <a>1.2</a>
       <b>1</b>
       <b>true</b>
       <c>what?</c>
       <d xsi:nil="true"/>
     </root>
    """)
    
    print objectify.dump(root)
    

    打印出来:

    root = None [ObjectifiedElement]
        a = 1 [IntElement]
          * attr1 = 'foo'
          * attr2 = 'bar'
        a = 1.2 [FloatElement]
        b = 1 [IntElement]
        b = True [BoolElement]
        c = 'what?' [StringElement]
        d = None [NoneElement]
          * xsi:nil = 'true'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-10
      • 1970-01-01
      • 2019-10-12
      • 2015-07-29
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多