【发布时间】:2011-02-17 21:10:43
【问题描述】:
我有一个简单的 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 正则表达式并不具备所有功能,但 the documentation I've found 表示我使用的每个功能都应该有效。
那么我误解了什么,为什么我的文档失败了?
【问题讨论】:
-
离题:'{1}'s 有什么原因吗?由于原子只匹配一次,它们看起来是多余的。
-
@outis:是的,它们是多余的,应该删除。他们所做的只是让正则表达式更难阅读,上帝知道正则表达式在这方面不需要任何帮助!
标签: python regex validation schema lxml