2013-08-23 71 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