您的位置:首页 > 其它

使用正则表达式进行xml数据验证

2008-05-01 05:09 746 查看
xml Schema是定义xml的数据定义文件,以.xsd作为文件的扩展名。它也以被用来定义一类xml文件。通常,一些特殊含义的数据不能通过系统预设的数据结构(类型)清楚地描述。
xml Schema 规范中声明:可以通过facet来限制(restriction)简单类型,从而产生一些新的原子类型(Atomic types)。
Facet有pattern, enumeration,等等;
这里要说的是其中非常有用的一项是:
pattern 正则表达式语言(regular expression language)
结合正则表达式的强大功能,就可以进行一些复杂的数据结构的描述
Examples可以通过xmlspy, xmlwrite,或js/vbs 等进行验证,下面举出了js验证的例子(需要msxml4.0支持)
有关定义 xml Schema 的信息,可以在W3C 的 xml Schema 规范的第一部分中找到。有关内置数据类型及其可用的局限性方面的信息,请检 查 xml Schema 规范的第二部分。关于 这两部分 xml Schema 规范的简易摘要,请查看 W3C Primer on xml Schema。
有关正则表达式,可以去http://www.regexlib.com/看看
examples:
/*** examples.xml ***/
<?xml version="1.0" encoding="gb2312"?>
<root xmlns:xsi="http://www.w3.org/2001/xmlSchema-instance" xsi:noNamespaceSchemaLocation="examples.xsd">
   <user>
  <name>test</name>
  <email>moonpiazza@hotmail.com</email>
  <ip>127.0.0.1</ip>
  <color>#000000</color>
   </user>
   <user>
  <name>guest</name>
  <email>guest@371.net</email>
  <ip>202.102.224.25</ip>
  <color>#FFFFFF</color>
   </user> 
</root>
/*** examples.xsd ***/
<?xml version="1.0" encoding="gb2312"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/xmlSchema">
<xsd:element name="root" type="Root"/>
<xsd:complexType name="Root">
<xsd:sequence>
 
<xsd:element name="user" type="User" minOccurs="0" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="User">
<xsd:sequence>
 
<xsd:element name="name" type="xsd:string"/>
 
<xsd:element name="email" type="Email" />
 
<xsd:element name="ip" type="IP" />
 
<xsd:element name="color" type="Color" />
</xsd:sequence>
</xsd:complexType>
<xsd:simpleType name="Email">
<xsd:restriction base="xsd:string">
 
<xsd:pattern value="([a-zA-Z0-9_/-/.] )@((/[[0-9]{1,3}/.[0-9]{1,3}/.[0-9]{1,3}/.)|(([a-zA-Z0-9/-] /.) ))([a-zA-Z]{2,4}|[0-9]{1,3})(/]?)"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="IP">
<xsd:restriction base="xsd:string">
 
<xsd:pattern value="(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])/.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)/.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)/.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="Color">
<xsd:restriction base="xsd:string">
 
<xsd:pattern value="#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: