xml 强制使用 xsd 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25907005/
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 12:05:21  来源:igfitidea点击:

Make an xsd element mandatory

xmlxsd

提问by Chandru Nagrani

I have an xml file that I am trying to validate against an xsd file. Works fine. I want to modify the xsd to make an element value mandatory. How do I do this so when I validate the xml file I want it to fail if the element FirstNameis blank (<FirstName></FirstName>)

我有一个 xml 文件,我正在尝试针对 xsd 文件进行验证。工作正常。我想修改 xsd 以强制使用元素值。我该怎么做,以便在验证 xml 文件时我希望它在元素FirstName为空时失败( <FirstName></FirstName>)

xml File

xml文件

<?xml version="1.0" encoding="utf-8" ?>
<Patient>
   <FirstName>Patient First</FirstName>
   <LastName>Patient Last</LastName>
</Patient>

xsd File

.xsd 文件

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Patient">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="FirstName" type="xs:string" />
        <xs:element name="LastName" type="xs:string" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

回答by Xstian

Mandatory

强制的

Attribute minOccursOptional. Specifies the minimum number of times the any element can occur in the parent element. The value can be any number >= 0. Default value is 1. (By default is mandatory)

属性minOccurs可选。指定 any 元素可以在父元素中出现的最小次数。该值可以是任何 >= 0 的数字。默认值为 1。 (默认情况下是强制性的)

<!-- mandatory true-->
<xs:element name="lastName" type="xs:string" />
<!-- mandatory false-->
<xs:element name="lastName" type="xs:string" minOccurs="0" />

Not Empty

不是空的

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