XML Schema: Element with attributes containing "restricted" text only
xml, xsd
Solution
Your question is more or less a duplicate of this question (just answered it).
Think in these terms:
- if your element has attributes and/or nested elements, it must be a complex type.
- if your element can have text, but no markup (nested elements) then it must be of simpleContent
- simpleContent can only be extended from a simple type (if you need to add an attribute). If you need additional constraints on the simple type, you need to specifically create a new simple type, restricting the base type, then extend that in a simple content.
This post on SO shows you an end-to-end example, of the above explanation. For your particular case:
<?xml version="1.0" encoding="utf-8" ?>
<!-- XML Schema generated by QTAssistant/XSD Module (http://www.paschidev.com) -->
<xsd:schema elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:simpleType name="tSomeRestrictedText">
<xsd:restriction base="xsd:string">
<xsd:pattern value="AAA"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:element name="some_element">
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base="tSomeRestrictedText">
<xsd:attribute name="my_attr" type="xsd:string"/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Problem
I want to define an element with some restricted text and an attribute ``` <some_element my_attr="data">some restricted text</some_element> ``` How can I create an element like this? I tried: ``` <complexType> <simpleContent> <restriction base="string"> <pattern value="AAA"></pattern> <attribute name="newattr" type="string"></attribute> </restriction> </simpleContent> </complexType> ``` But getting error msg: Complex Type Definition Representation Error for type '#AnonType_childparent'. When is used, the base type must be a complexType whose content type is simple, or, only if restriction is specified, a complex type with mixed content and emptiable particle, or, only if extension is specified, a simple type. 'string' satisfies none of these conditions. And then tried something like this ``` <complexType> <complexContent> <extension base="string"> <attribute name="attr" type="string"></attribute> </extension> </complexContent> </complexType> ``` This time error was (This time I didn't add any restriction; this was for test purpose only): Complex Type Definition Representation Error for type '#AnonType_childparent'. When is used, the base type must be a complexType. 'string' is a simpleType. I am not getting clearly what the errors are implying? Is there some better explanation of error text available?