XSD 元素不为空或 Xml 的空约束?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4408158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 13:26:12  来源:igfitidea点击:

XSD Element Not Null or Empty Constraint For Xml?

xmlxsd

提问by Ramakrishnan

This is my sample XML Code:

这是我的示例 XML 代码:

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

I am using:

我在用:

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

The XSD Should be validate lastNameas not null or empty.

XSD 应验证lastName为非 null 或空。

回答by Kamal

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>

回答by sri

<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>

回答by Gab

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>

回答by Nic Gibson

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

@Kamal 在这里给了你基本正确的答案。这就是为什么 - nillable似乎总是会引起问题。实际上,您可以将允许此元素上属性nillable视为含义。该XML模式规范描述的nillable作为带外信号-它基本上用来表示NULL到数据库。xsi:nil

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

你想要的是一个元素,它必须至少是@Kamal 给出的一个字符长

回答by mrx

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>