Search code examples
xmlxsdschemarestriction

XML Schema: SimpleType element that must not be empty and has attributes


How do you declare an element

  • with non-complex content (i.e. "text" and not a child element)
  • that also has attributes
  • and whose text node must not be empty

in XML Schema?

An example instance would be:

<my-element x="aaa" y="bbb">This text node must not be empty!<my-element>

Solution

  • The trick is to first restrict a simple type so that it needs to be at least one character long, and then extend said restricted type accordingly:

    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
      <xs:element name="my-element">
        <xs:complexType>
          <xs:simpleContent>
            <xs:extension base="at-least-one-character">
              <xs:attribute name="x" type="xs:string"/>
              <xs:attribute name="y" type="xs:string"/>
            </xs:extension>
          </xs:simpleContent>
        </xs:complexType>
      </xs:element>
      
      <xs:simpleType name="at-least-one-character">
        <xs:restriction base="xs:token">
          <xs:minLength value="1"/>
        </xs:restriction>
      </xs:simpleType>
    </xs:schema>
    

    I just had this problem and wanted to share the solution - maybe someone finds this helpful.