你如何自定义lxml objectify来解析INF作为字符串而不是浮点数?

时间:2014-05-20 15:38:07

标签: python xml lxml

使用python lxml和objectify,它将INF转换为浮点数。有没有办法将INF输出为字符串而不是浮点数?

from lxml import objectify


value='''
    <outside>
        <inside>INF</inside>
    </outside>
'''
root = objectify.fromstring(value)
inside = root.inside 
print inside, inside.__class__

输出:

inf <type 'lxml.objectify.FloatElement'>

1 个答案:

答案 0 :(得分:0)

inside标记上设置pytype attribute

<outside xmlns:py="http://codespeak.net/lxml/objectify/pytype">
    <inside py:pytype='str'>INF</inside>
</outside>

演示:

>>> from lxml import objectify
>>> value = '''
...     <outside xmlns:py="http://codespeak.net/lxml/objectify/pytype">
...         <inside py:pytype='str'>INF</inside>
...     </outside>
... '''
>>> root = objectify.fromstring(value)
>>> inside = root.inside
>>> print inside, inside.__class__
INF <type 'lxml.objectify.StringElement'>