I am new to XML schema and I am try to understand how they work. I have written a simple schema.Below is my xml schema.
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="employees" type="comType"/>
<xs:complexType name="comType">
<xs:sequence>
<xs:element ref="employee" maxOccurs="2"/>
</xs:sequence>
</xs:complexType>
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
</xs:sequence>
<xs:attribute name="id" type="xs:integer" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
However I am bit confused what XML will be valid for this schema.When I am validating both of the below XML using notpad++ both of the below XML are not giving an error as I am expecting that XML with root element of employees should the correct one.
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee id="1">
<name>xxxx</name>
<address>xxx</address>
</employee>
<employee id="2">
<name>yyyyy</name>
<address>yyy</address>
</employee>
</employees>
and second XML is
<?xml version="1.0" encoding="UTF-8"?>
<employee id="1">
<name>Deepak</name>
<address>909</address>
</employee>
ANd the schema is
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="employees" type="comType"/>
<xs:complexType name="comType">
<xs:sequence>
<xs:element ref="employee" maxOccurs="2"/>
</xs:sequence>
</xs:complexType>
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
</xs:sequence>
<xs:attribute name="id" type="xs:integer" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
Need help...
Both Xml instances are correct, as in Xml Schema, any globally defined
<element>
can serve as a root element. This is also discussed in answers to this other question.As you have defined both
employees
andemployee
with the<xsd:element>
element on the root level of your schema (i.e. directly nested within the<xsd:schema>
element), either of these can be used as a root for an Xml instance document of your schema.To prevent
employee
from being eligible as a root element, you could either completely inline the definition of theemployee
element instead of using<xs:element ref="employee" maxOccurs="2"/>
, or you could name the content of theemployee
element and define thatcomplexType
on the schema root level, so you get a re-usable complex type that you can then indicate as the type of theemployee
element.