xsd:SimpleType:如何将属性限制为特定值和正则表达式值

时间:2014-09-25 21:35:44

标签: regex xsd restrictions

我有一个可以是任何字符串的属性,但如果它有开始和结束括号"^[.*]$" - 它必须只是以下特定值之一:

"[EVENT]"  

"[PROTOCOL]"

所以,"[EVENT]""[PROTOCOL]""SomeString" - 是正确的,但"[SomeString]" - 不是。

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:3)

使用xs:simpleType和正则表达式来限制基本xs:string类型。您可以拥有多个xs:pattern来简化替代模式。元素必须匹配其中一个模式,否则验证将失败。由于模式是正则表达式,因此当用作文字时,必须转义“[”和“]”等特殊字符。

XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="root">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="elem" type="myElemType" maxOccurs="unbounded"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="myElemType">
    <xs:attribute name="attrib" type="myAttribType"/>
  </xs:complexType>

  <xs:simpleType name="myAttribType">
    <xs:restriction base="xs:string">
      <xs:pattern value="\[EVENT\]"/><!-- "[EVENT]": okay -->
      <xs:pattern value="\[PROTOCOL\]"/><!-- "[PROTOCOL]": okay -->
      <xs:pattern value="[^\[].*"/><!-- Starts with anything but "[": okay -->
    </xs:restriction>
  </xs:simpleType>
</xs:schema>

XML:

<root>
  <elem attrib="[EVENT]"/>
  <elem attrib="[PROTOCOL]"/>
  <elem attrib="SomeString"/>
  <elem attrib="SomeString]"/>
  <elem attrib="   [SomeString]   "/>
  <!-- All the above are okay; the ones below fail validation -->
  <elem attrib="[SomeString]"/>
  <elem attrib="[SomeString"/>
</root>

将正则表达式修改为您的心脏内容,例如,使示例失败,并使用前导和/或尾随空格。

已编辑以反映OP的评论“[SomeString”也应无效。

答案 1 :(得分:2)

我喜欢@Burkart更好地使用单独的xs:pattern元素(+1),但我等待评论中的澄清("[SomeString"没有结束括号应该无效),所以我'无论如何都会发布它,以防有人发现它有用。将正则表达式读作括号内的 EVENT或PROTOCOL或任何不以括号开头或结尾的字符串。

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="root">
    <xs:complexType>
      <xs:attribute name="attr">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:pattern value="\[(EVENT|PROTOCOL)\]|[^\[].*[^\]]"/>
          </xs:restriction>
        </xs:simpleType>
      </xs:attribute>
    </xs:complexType>
  </xs:element>
</xs:schema>
相关问题