2012-07-04 11 views
6

ví dụ tập tin xml của tôi chứa:Có cách nào hay bất kỳ khuôn khổ nào trong python để tạo một mô hình đối tượng từ một xml?

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

và tôi muốn lấy một đối tượng từ xml ví dụ trở lại cấu trúc đối tượng được như thế này

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=[] 

Trả lời

4

tôi đã tìm thấy câu trả lời của tôi tôi được sử dụng trong gói lxml

đây là mã mẫu:

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) 

bản in:

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' 
Các vấn đề liên quan