I have an XML document which is like:
<?xml version="1.0" encoding="UTF-8"?>
<html2filename xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../xsd/mapper.xsd">
<htmlFile filename="N5670A">
<variant>1</variant>
<groups>
<group>
<name>Removing thermostat</name>
</group>
<someOtherElements>asdasd</someOtherElements>
</groups>
</htmlFile>
</html2filename>
Now element "groups" -> "group" -> "name" -> should have one constraint: It should be optional if "variant" has the value 3. If not it should be required.
Can XSD handle that? If yes, how?
An xs:assert
can implement such a value-sensitive constraint:
<xs:assert test="(variant = 3) or groups/group/name"/>
Here it is in the context of a complete XSD that will validate the XML you provided:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
vc:minVersion="1.1">
<xs:element name="html2filename">
<xs:complexType>
<xs:sequence>
<xs:element name="htmlFile">
<xs:complexType>
<xs:sequence>
<xs:element name="variant"/>
<xs:element name="groups">
<xs:complexType>
<xs:sequence>
<xs:element name="group" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="name" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="someOtherElements"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="filename"/>
<xs:assert test="(variant = 3) or groups/group/name"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.