2
當客觀化元素被打印在控制檯上,前導零丟失,但它在保留.text
:lxml.objectify和前導零
>>> from lxml import objectify
>>>
>>> xml = "<a><b>01</b></a>"
>>> a = objectify.fromstring(xml)
>>> print(a.b)
1
>>> print(a.b.text)
01
據我瞭解,objectify
自動使b
元素IntElement
類實例。但是,它也做,即使我嘗試明確設置的類型與XSD schema:
from io import StringIO
from lxml import etree, objectify
f = StringIO('''
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="a" type="AType"/>
<xsd:complexType name="AType">
<xsd:sequence>
<xsd:element name="b" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
''')
schema = etree.XMLSchema(file=f)
parser = objectify.makeparser(schema=schema)
xml = "<a><b>01</b></a>"
a = objectify.fromstring(xml, parser)
print(a.b)
print(type(a.b))
print(a.b.text)
打印:
1
<class 'lxml.objectify.IntElement'>
01
我怎麼能強迫objectify
這個b
元素識別爲一個字符串元素?
有趣的行爲,很高興看到它解釋!謝謝,很好的回答。 – alecxe