当在控制台上打印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元素识别为字符串元素?

最佳答案

根据文档和观察到的行为,看来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'.




尽管how data types are matched上的objectify文档提到了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

关于python - lxml.objectify和前导零,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35960223/

10-09 19:43