2013-08-23 69 views
-4

docs總是寫得很差,例子更有幫助。如何將xml對象轉換爲python對象?

這是我的xml文件:

<wordbook> 
    <item> 
    <name>engrossment</name> 
    <phonetic><![CDATA[ɪn'grəʊsmənt]]></phonetic> 
    <meaning><![CDATA[n. 正式繕寫的文件,專注]]></meaning> 
    </item> 
    <item> 
    <name>graffiti</name> 
    <phonetic><![CDATA[ɡrəˈfi:ti:]]></phonetic> 
    <meaning><![CDATA[n.在牆上的亂塗亂寫(複數形式)]]></meaning> 
    </item> 
    <item> 
    <name>pathology</name> 
    <phonetic><![CDATA[pæˈθɔlədʒi:]]></phonetic> 
    <meaning><![CDATA[n. 病理(學);〈比喻〉異常狀態]]></meaning> 
    </item> 
<wordbook> 

這是我的Python類:

class Item(Base): 
    name = Column(String(50), primary_key=True) 
    phonetic = Column(String(50), default='') 
    meaning = Column(UnicodeText, nullable=False) 

選擇你喜歡


終於XML解析器,我用xmltodict解析,lxml寫入:

from lxml import etree 

wordbook = etree.Element('wordbook') 
for one in items: 
    item = etree.Element('item') 
    name = etree.Element('name') 
    name.text = one.name 
    phonetic = etree.Element('phonetic') 
    phonetic.text = etree.CDATA(one.phonetic) 
    meaning = etree.Element('meaning') 
    meaning.text = etree.CDATA(one.meaning) 
    if 1: 
     item.append(name) 
     item.append(phonetic) 
     item.append(meaning) 
    wordbook.append(item) 
s = etree.tostring(wordbook, pretty_print=True, encoding='utf8') 
print s 
+0

嘗試在beautifulsoup文檔和計算器上找到示例 – metaphy

+1

「文檔總是寫得很糟糕」 - 是的,不。我唯一要說的是[RTFM](http://wiki.python.org/moin/PythonXml)。 – l4mpi

+0

sqlalchemy的github源代碼中有很多例子,所以我可以grep它,例子最適合初學者 – metaphy

回答

1

我會用xmltodict去:

# -*- coding: utf-8 -*- 
import xmltodict 

data = """<wordbook> 
    <item> 
    <name>engrossment</name> 
    <phonetic><![CDATA[ɪn'grəʊsmənt]]></phonetic> 
    <meaning><![CDATA[n. 正式繕寫的文件,專注]]></meaning> 
    </item> 
    <item> 
    <name>graffiti</name> 
    <phonetic><![CDATA[ɡrəˈfi:ti:]]></phonetic> 
    <meaning><![CDATA[n.在牆上的亂塗亂寫(複數形式)]]></meaning> 
    </item> 
    <item> 
    <name>pathology</name> 
    <phonetic><![CDATA[pæˈθɔlədʒi:]]></phonetic> 
    <meaning><![CDATA[n. 病理(學);〈比喻〉異常狀態]]></meaning> 
    </item> 
</wordbook>""" 

data = xmltodict.parse(data, encoding='utf-8') 

for item in data['wordbook']['item']: 
    print item['name'] 

打印:

engrossment 
graffiti 
pathology 

您還可以使用BeautifulSouplxml - 這是一個品味的問題。這個想法幾乎相同 - 遍歷item標籤並在循環中實例化Item

希望有所幫助。

+0

謝謝,我知道一年前如何在java中解析和編寫xml。 – metaphy

+0

在您的示例幫助下,在幾分鐘內學習xml解析是很好的。一年前,我花了一週或更長時間。 – metaphy