I need to validate XML using the following XSD
<xs:element name="root" type="rootType"/>
<xs:element name="names" type="nameType"/>
<xs:complexType name="rootType" mixed="true">
<xs:sequence>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="names" minOccurs="0" maxOccurs="unbounded" type="nameType"/>
<xs:element name="root" minOccurs="0" maxOccurs="unbounded" type="rootType"/>
</xs:choice>
</xs:sequence>
<xs:attribute name="name" type="xs:string"/>
</xs:complexType>
<xs:complexType name="nameType" mixed="true">
<xs:sequence>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="names" minOccurs="0" maxOccurs="unbounded" type="nameType"/>
<xs:element name="root" minOccurs="0" maxOccurs="unbounded" type="rootType"/>
</xs:choice>
</xs:sequence>
<xs:attribute name="name" type="xs:string"/>
</xs:complexType>
such that, the XSD should not allow the root element in the XML to have a "name" attribute.
Eg: The XSD should consider the following XML as valid
<root>
<names name="abc"></names>
<root name="xyz"></root>
</root>
and the following as invalid, since the root element of the xml has a name attribute.
<root name="rootElement">
<names name="abc"></names>
<root name="xyz"></root>
</root>
However, if the same element appears as a child element, then it can have a name attribute. Please let us know if this is feasible using XSD, if so how can we do it?
Define rootType without a name attribute:
<xs:complexType name="rootTypeWithoutName" mixed="true">
<xs:sequence>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="names" minOccurs="0" maxOccurs="unbounded" type="nameType"/>
<xs:element name="root" minOccurs="0" maxOccurs="unbounded" type="rootTypeWithName"/>
</xs:choice>
</xs:sequence>
</xs:complexType>
then define an extended type that allows the name:
<xs:complexType name="rootTypeWithName" mixed="true">
<xs:extension base="rootTypeWithoutName">
<xs:attribute name="name" type="xs:string"/>
</xs:extension>
</xs:complexType>
In the global element declaration for root, use type="rootTypeWithoutName"
. In the local element declaration for a nested root element (as shown above), use the type rootTypeWithName
.
I haven't tested this, so there may be syntax slips, but the principle should be sound.
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.