开发者

XSD Element Not Null or Empty Constraint For Xml?

This is my sample XML Code:

<bestContact>
<firstName><![CDATA[12345]]></firstName>
<lastName />
</bestContact>

I am using:

<xs:element name="lastName" type="xs:string" minOccurs="1" nillable="false"/>

The 开发者_JAVA百科XSD Should be validate lastName as not null or empty.


Try

<xs:element name="lastName" minOccurs="1" nillable="false">
  <xs:simpleType>
     <xs:restriction base="xs:string">
       <xs:minLength value="1"/>
     </xs:restriction>
  </xs:simpleType>
</xs:element>


<xsd:element name="lastName" type="NonEmptyString" nillable="false"/>

<xsd:simpleType name="NonEmptyString">
  <xsd:restriction base="xs:string">
    <xsd:minLength value="1" />
    <xsd:pattern value=".*[^\s].*" />
  </xsd:restriction>
</xsd:simpleType>


This is IMHO a better pattern:

<xs:simpleType name="NonEmptyString">
   <xs:restriction base="xs:string">
      <xs:pattern value="^(?!\s*$).+" />
   </xs:restriction>
</xs:simpleType>

or

<xs:simpleType name="NonEmptyStringWithoutSpace">
   <xs:restriction base="xs:string">
      <xs:pattern value="\S+"/>
   </xs:restriction>
</xs:simpleType>


@Kamal has given you basically right answer here. This is why - nillable always seems to cause problems. Effectively, you can consider nillable as meaning allow the xsi:nil attribute on this element. The XML Schema spec describes nillable as an out of band signal - it's basically used to indicate NULL to databases.

What you want is an element that must be at least one character long as given by @Kamal


This was my favourite solution.

<xs:simpleType name="NonEmptyString">
    <xs:restriction base="xs:string">
        <xs:pattern value="[\s\S]*[^ ][\s\S]*"/>
    </xs:restriction>
</xs:simpleType>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜