问题
I have the following XSD (part of the XSD)
<xs:element name="sourceValue" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:normalizedString">
<xs:attribute name="label" type="xs:normalizedString"
use="required"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
In my XML I have:
<?xml version="1.0" encoding="UTF-8"?>
<Record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="assertion.xsd">
<SSN>33333332</SSN>
<sourceValue label="nrA">33333333</sourceValue>
<sourceValue label="nrB">111111111</sourceValue>
<Data>
<Patient>
<DateOfBirth>03-04-2000</DateOfBirth>
<Sexe>M</Sexe>
<Name>Patient A</Name>
</Patient>
</Data>
</Record>
I want to change my XSD in such a way that when sourceValue with label="nrA" is mandatory, but with label="nrB" is optional. But I cannot figure out how to do this.
回答1:
XSD 1.0
Not possible. Instead, you should use different element names for the two cases.
XSD 1.1
Different element names are still recommended, but if you must follow your current approach, you can use assertions:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1">
<xs:element name="Record">
<xs:complexType>
<xs:sequence>
<xs:element name="SSN" type="xs:string"/>
<xs:element ref="sourceValue"/>
<xs:element ref="sourceValue" minOccurs="0"/>
<xs:element name="Data">
<xs:complexType>
<xs:sequence>
<xs:element name="Patient">
<xs:complexType>
<xs:sequence>
<xs:element name="DateOfBirth" type="xs:string"/>
<xs:element name="Sexe" type="xs:string"/>
<xs:element name="Name" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:assert test="sourceValue[1]/@label = 'nrA'"/>
<xs:assert test="not(sourceValue[2]) or sourceValue[2]/@label = 'nrA'"/>
</xs:complexType>
</xs:element>
<xs:element name="sourceValue">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="label" type="xs:string"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:schema>
来源:https://stackoverflow.com/questions/31367677/require-element-based-on-position-and-attribute-value