lxml.objectify和前导零

3
当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 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 元素识别为字符串元素?
1个回答

2
根据文档和观察到的行为,似乎 XSD Schema 仅用于验证,但在确定属性数据类型的过程中并没有涉及。例如,在 XSD 中声明元素类型为 integer,但是在 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'.

尽管在如何匹配数据类型的文档中提到了XML Schema xsi:type(链接部分中的第4点),但那里的示例代码表明它是指直接在实际的XML元素中添加xsi:type属性,而不是通过一个单独的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

有趣的行为,很高兴看到它被解释了!谢谢,非常好的答案。 - alecxe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接