如何使用正则表达式验证xml中的元素

时间:2019-07-08 17:46:55

标签: xml

我在这里尝试验证参考号字段,该字段应仅允许使用'A'至'Z','0'至'9','-'和'_'等特定字符。我该怎么做?

<field name="txtNumeroDossier" type="texte" maxlength="15" focus="true">
    <description_f>Votre numéro de référence</description_f>
    <description_a>Your reference number</description_a>
</field>

1 个答案:

答案 0 :(得分:0)

您需要使用XSD schema进行验证,创建新的.xsd文件:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" version="SNAPSHOT" elementFormDefault="qualified" attributeFormDefault="unqualified">
  <!-- create new simple type for description fields,
       restriction by pattern will validate by regexp -->
  <xs:simpleType name="description">
    <xs:restriction base="xs:string">
      <xs:pattern value="[a-z0-9\-_]+"/>
    </xs:restriction>
  </xs:simpleType>
  <!-- field root element type declaration -->
  <xs:complexType name="field">
    <xs:all>
      <!-- description elements of type description with validation -->
      <xs:element name="description_f" type="description"/>
      <xs:element name="description_a" type="description"/>
    </xs:all>
    <!-- attributes -->
    <xs:attribute name="name" type="xs:string"/>
    <xs:attribute name="type" type="xs:string"/>
    <xs:attribute name="maxlength" type="xs:string"/>
    <xs:attribute name="focus" type="xs:string"/>
  </xs:complexType>
  <!-- root element declaration of type field -->
  <xs:element name="field" type="field"/>
</xs:schema>