当 objectify 元素打印在控制台上时,前导零会丢失,但它会保留在.text
:
>>> 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架构 http://lxml.de/objectify.html#asserting-a-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)
Prints:
1
<class 'lxml.objectify.IntElement'>
01
我怎样才能强迫objectify
认识到这一点b
元素作为字符串元素?
根据文档和观察到的行为,似乎XSD Schema
仅用于验证,但不参与确定属性数据类型的过程。
例如,当一个元素被声明为类型时integer
在 XSD 中,但是 XML 中的实际元素的值为x01
,元素无效异常被正确引发:
f = StringIO(u'''
<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:integer" />
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
''')
schema = etree.XMLSchema(file=f)
parser = objectify.makeparser(schema=schema)
xml = '''<a><b>x01</b></a>'''
a = objectify.fromstring(xml, parser)
# the following exception raised:
# lxml.etree.XMLSyntaxError: Element 'b': 'x01' is not a valid value of....
# ...the atomic type 'xs:integer'.
Despite objectify
文档关于数据类型如何匹配 http://lxml.de/objectify.html#how-data-types-are-matched提到关于XML 架构 xsi:类型(链接部分中的第 4 号),那里的示例代码表明这意味着通过增加xsi:type
属性直接位于实际的 XML 元素中,不通过单独的 XSD 文件,例如:
xml = '''
<a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<b xsi:type="string">01</b>
</a>
'''
a = objectify.fromstring(xml)
print(a.b) # 01
print(type(a.b)) # <type 'lxml.objectify.StringElement'>
print(a.b.text) # 01
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)