我有一个简单的doc.xml
文件,其中包含一个带有 Timestamp 属性的根元素:
<?xml version="1.0" encoding="utf-8"?>
<root Timestamp="04-21-2010 16:00:19.000" />
我想根据我的简单验证此文档,schema.xsd
以确保时间戳的格式正确:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
<xs:complexType>
<xs:attribute name="Timestamp" use="required" type="timeStampType"/>
</xs:complexType>
</xs:element>
<xs:simpleType name="timeStampType">
<xs:restriction base="xs:string">
<xs:pattern value="(0[0-9]{1})|(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3} ([0-1]{1}[0-9]{1}|2[0-3]{1}):[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}.[0-9]{3}" />
</xs:restriction>
</xs:simpleType>
</xs:schema>
所以我使用lxml Python 模块并尝试执行简单的模式验证并报告任何错误:
from lxml import etree
schema = etree.XMLSchema( etree.parse("schema.xsd") )
doc = etree.parse("doc.xml")
if not schema.validate(doc):
for e in schema.error_log:
print e.message
我的 XML 文档验证失败,并显示以下错误消息:
Element 'root', attribute 'Timestamp': [facet 'pattern'] The value '04-21-2010 16:00:19.000' is not accepted by the pattern '(0[0-9]{1})|(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3} ([0-1]{1}[0-9]{1}|2[0-3]{1}):[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}.[0-9]{3}'.
Element 'root', attribute 'Timestamp': '04-21-2010 16:00:19.000' is not a valid value of the atomic type 'timeStampType'.
所以看起来我的正则表达式一定有问题。但是当我尝试在命令行验证正则表达式时,它通过了:
>>> import re
>>> pat = '(0[0-9]{1})|(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3} ([0-1]{1}[0-9]{1}|2[0-3]{1}):[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}.[0-9]{3}'
>>> assert re.match(pat, '04-21-2010 16:00:19.000')
>>>
我知道 XSD 正则表达式并不具备所有功能,但我发现的文档表明我使用的每个功能都应该有效。
那么我误解了什么,为什么我的文档失败了?