2016-03-12 80 views
2

當客觀化元素被打印在控制檯上,前導零丟失,但它在保留.textlxml.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元素識別爲一個字符串元素?

回答

1

根據文檔和觀察到的行爲,似乎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'. 

儘管objectify文檔how data types are matched提到了關於XML Schema 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 
+0

有趣的行爲,很高興看到它解釋!謝謝,很好的回答。 – alecxe