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 模式显式设置类型,它也会这样做:

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为字符串元素?

4

1 回答 1

2

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

尽管有关XML Schema xsi:type (链接部分中的第 4 位)提到了有关如何匹配数据类型的objectify文档,但那里的示例代码表明这意味着直接在实际 XML 元素中添加属性,而不是通过单独的 XSD 文件,例如 :xsi:type

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
于 2016-03-13T03:03:06.560 回答