我正在尝试创建一个xsd来验证一些xml。如果没有找到成员元素,我希望xsd失败,我想添加minOccurs =" 1"会实现这个,但由于某种原因,即使传递0成员元素,它也会通过。
<xs:attributeGroup name="memberAttributes">
<xs:annotation>
<xs:documentation>Set of attributes for member element</xs:documentation>
</xs:annotation>
<xs:attribute name="employeeid" type="xs:string" use="required"/>
<xs:attribute name="dob" type="Shortdate" use="required"/>
<xs:attribute name="gender" type="Gender" use="required"/>
<xs:attribute name="salary" use="required">
<xs:simpleType>
<xs:restriction base="Amount2dp">
<xs:totalDigits value="13"/>
<xs:maxInclusive value="99999999999.99"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="postcode" type="Postcode" use="required"/>
</xs:attributeGroup>
<xs:element name="member">
<xs:annotation>
<xs:documentation>Member element</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:attributeGroup ref="memberAttributes"/>
</xs:complexType>
</xs:element>
<xs:element name="members">
<xs:annotation>
<xs:documentation>Set of member elements</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence minOccurs="1" maxOccurs="unbounded">
<xs:element ref="member"/>
</xs:sequence>
</xs:complexType>
</xs:element>
答案 0 :(得分:1)
添加minOccurs="1"
确实是指定元素是必需的方式。您的XSD应该达到您所寻求的结果。
确认:您的XSD独立:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:attributeGroup name="memberAttributes">
<xs:annotation>
<xs:documentation>Set of attributes for member element</xs:documentation>
</xs:annotation>
<xs:attribute name="employeeid" type="xs:string" use="required"/>
<xs:attribute name="dob" use="required"/>
<xs:attribute name="gender" use="required"/>
<xs:attribute name="salary" use="required">
<xs:simpleType>
<xs:restriction base="xs:decimal">
<xs:totalDigits value="13"/>
<xs:maxInclusive value="99999999999.99"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="postcode" use="required"/>
</xs:attributeGroup>
<xs:element name="member">
<xs:annotation>
<xs:documentation>Member element</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:attributeGroup ref="memberAttributes"/>
</xs:complexType>
</xs:element>
<xs:element name="members">
<xs:annotation>
<xs:documentation>Set of member elements</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence minOccurs="1" maxOccurs="unbounded">
<xs:element ref="member"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
会发现此XML文档有效:
<?xml version="1.0" encoding="UTF-8"?>
<members>
<member employeeid="" dob="" gender="" salary="1.0" postcode=""/>
<member employeeid="" dob="" gender="" salary="1.0" postcode=""/>
</members>
但是会发现此XML文档无效:
<?xml version="1.0" encoding="UTF-8"?>
<members/>
并会发出如下错误:
[错误] try.xml:3:52:cvc-complex-type.2.4.b:元素的内容 '成员'不完整。预计会有一个“{member}”。
最后注意事项:在minOccurs
上放置maxOccurs
和xs:sequence
表示整个序列的必要性和基数限制。在这种情况下,序列中只有一个member
元素,因此表单是等效的,但是当xs:sequence
有更多子元素时要注意区别。