我必须验证格式为 09.02.2015 (DD.MM.YYYY) 和时间 14:05 (HH:MM) 的日期,但找不到执行此操作的方法。
这是一个例子:
XML:
<?xml version="1.0"?>
<root>
<testdate>09.02.2015</testdate>
<testtime>14:05</testtime>
</root>
XSD:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<!-- Root element -->
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="testdate" type="zsdate"/>
<xs:element name="testtime" type="zstime"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<!-- Date format used to validate dates formatted like 01.01.2015 -->
<xs:simpleType name="zsdate">
<xs:restriction base="xs:date">
<xs:pattern value="^(0[1-9]|[12][0-9]|3[01]).(0[1-9]|1[012]).(19|20)\d\d$"/>
</xs:restriction>
</xs:simpleType>
<!-- Time format used to validate times formatted like 11:55, 23:59 etc. -->
<xs:simpleType name="zstime">
<xs:restriction base="xs:time">
<xs:pattern value="^(0[0-9]|[1][0-9]|2[1-3]):([0-5][1-9])$"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
我已经尝试使用 notepad++ XML 插件和这个 XML validator 来验证 XML .
Notepad++ 输出:
Validation of current file using XML schema:
ERROR: Element 'testdate': '09.02.2015' is not a valid value of the atomic type 'zsdate'.
ERROR: Element 'testtime': '14:05' is not a valid value of the atomic type 'zstime'.
使用 Regular Expression Tester 测试正则表达式时, 它匹配正确。
我尝试将类型从 xs:date
和 xs:time
更改为 xs:string
,但验证结果相同。
知道我做错了什么吗?
最佳答案
您的日期和时间要求不是 xs:date
和 xs:time
的适当限制。如果是的话,进行这些更改会起作用(但不会像您希望的那样严格):
<xs:element name="testdate" type="xs:date"/>
<xs:element name="testtime" type="xs:time"/>
因此,要使用您的模式,您必须将它们基于 xs:string
。您还必须考虑到,在 XSD 的 xs:pattern
正则表达式中,开头已经有一个隐式的 ^
anchor 和 $
anchor 在模式的末尾。删除您添加的额外内容可以消除您遇到的问题。
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<!-- Root element -->
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="testdate" type="zsdate"/>
<xs:element name="testtime" type="zstime"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<!-- Date format used to validate dates formatted like 01.01.2015 -->
<xs:simpleType name="zsdate">
<xs:restriction base="xs:string">
<xs:pattern value="(0[1-9]|[12][0-9]|3[01]).(0[1-9]|1[012]).(19|20)\d\d"/>
</xs:restriction>
</xs:simpleType>
<!-- Time format used to validate times formatted like 11:55, 23:59 etc. -->
<xs:simpleType name="zstime">
<xs:restriction base="xs:string">
<xs:pattern value="(0[0-9]|[1][0-9]|2[1-3]):([0-5][1-9])"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
https://stackoverflow.com/questions/28410780/