Reputation: 127
I have on the XML:
<Devices>
<Device name="Phone" number="123456789"/>
<Device name="Computer" ip="192.168.0.1"/>
</Devices>
and I want to set an Schema for this, where I have 'devices' and I can declare a device, but if the device has the name="phone" a number has to be declared as required, but if the device is name="computer", well, the ip is required just for 'computer'
is there a way to do this, is it possible?
Upvotes: 4
Views: 2918
Reputation: 725
This would be the XML schema
<xs:schema elementFormDefault="qualified" version="1.0"
targetNamespace="stackoverflow" xmlns:tns="stackoverflow"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Devices" type="tns:deviceListType" />
<xs:complexType name="deviceListType">
<xs:sequence>
<xs:element name="Device" type="tns:deviceType" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="deviceType">
</xs:complexType>
<xs:complexType name="computerType">
<xs:complexContent>
<xs:extension base="tns:deviceType">
<xs:attribute name="name">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Computer" />
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="ip" />
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="phoneType">
<xs:complexContent>
<xs:extension base="tns:deviceType">
<xs:attribute name="name">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Phone" />
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="number" />
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>
And this would be a sample XML document
<sf:Devices xmlns:sf="stackoverflow"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="stackoverflow test.xsd">
<sf:Device xsi:type="sf:computerType" name="Computer" ip="1"/>
<sf:Device xsi:type="sf:phoneType" name="Phone" number="2"/>
</sf:Devices>
Sorry if the original XSD sample was confusing.
Upvotes: 3