【问题标题】:Make sure string is not empty in XML validation with XSD使用 XSD 确保 XML 验证中的字符串不为空
【发布时间】:2020-01-23 19:21:34
【问题描述】:

我有一个XML 文件,例如如下所示。我想确保menonic 始终存在并且不是空字符串。

我像这样在我的 XSD 中设置了use="required"

<xs:attribute type="xs:string" name="mnemonic" use="required"/>
它确保该字段存在。 但是当字符串为空时,如下所示 <recipeStructureDef mnemonic="" title="Recipe.Bread"> 它通过了验证。

有什么方法可以检查字符串是否不是空字符串?

谢谢,请在下面找到 xml 和 xsd 文件。

<recipeStructureDef mnemonic="Rice Bag" title="Recipe.Bread">
            <description>           
            </description>

            <parametersTab>
                <parameterTabDef title="Main Parameters">
                    <parameterGroup title="Product Rice">
                    </parameterGroup>
                </parameterTabDef>
             </parametersTab>
</recipeStructureDef>


需要操作:

  <xs:complexType name="recipeStructureDefType">
    <xs:sequence>
      <xs:element type="xs:string" name="description"/>
      <xs:element type="parametersTabType" name="parametersTab"/>
    </xs:sequence>
    <xs:attribute type="xs:string" name="mnemonic" use="required"/>
    <xs:attribute type="xs:string" name="title"/>
  </xs:complexType>

【问题讨论】:

    标签: xml xsd freemarker xsd-validation xml-validation


    【解决方案1】:

    属性@mnemonic必须存在:

    <xs:attribute name="mnemonic" use="required" type="nonEmptyString"/>
                                  ^^^^^^^^^^^^^^
    

    @mnemonic 的属性值不能为空:

    <xs:simpleType name="nonEmptyString">
      <xs:restriction base="xs:string">
        <xs:minLength value="1"/>
      </xs:restriction>
    </xs:simpleType>
    

    【讨论】:

      【解决方案2】:

      简单类型 xs:string 是一个没有规则或约束的纯字符串。您需要创建一个带有一些约束的简单类型(在 XML Schema 中称为“方面”),并在助记符属性的定义中使用该简单类型。

          <xs:simpleType name="mnemonicType" >
            <xs:restriction base="xs:string">
              <xs:minLength value="1" />
            </xs:restriction>
          <xs:simpleType>
      
          <xs:complexType name="recipeStructureDefType">
            <xs:sequence>
              <xs:element type="xs:string" name="description"/>
              <xs:element type="parametersTabType" name="parametersTab"/>
            </xs:sequence>
      
            <xs:attribute type="mnemonicType" name="mnemonic" use="required"/>
            <xs:attribute type="xs:string" name="title"/>
          </xs:complexType>
      

      您可能希望指定一个以上字符的最小长度,而 minLength 方面是可用于限制简单值的众多方面之一。查看 XML Schema 规范以获取完整列表:https://www.w3.org/TR/xmlschema-2/#built-in-primitive-datatypes

      【讨论】:

      • 为什么要发布另一个与already existing answer 基本相同的答案?
      • 道歉 - 在编辑我的答案时被延迟,并且在发布之前没有刷新。
      猜你喜欢
      • 2014-05-08
      • 2019-11-03
      • 2013-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      • 2018-01-02
      • 2013-05-21
      相关资源
      最近更新 更多