Restricting empty elements in xsd

validation, xml, xsd

Solution

If you're trying to prevent the element from appearing at all, you can mark it with `maxOccurs="0"`. I'm guessing this isn't what you're after, so if you're trying to make sure there are always attributes attached to the complex element, then you have to specify `usage="required"` on at least one of the attributes or use an attribute group. If `myElement` is a simple type and you want to make sure it has a value, then you could always restrict the type of it. If you want a non-zero string, then you could do:

<xsd:element name="myElement">
    <xsd:simpleType>
        <xsd:restriction base="xsd:string">
            <xsd:minLength value="1" />
        </xsd:restriction>
    </xsd:simpleType>
</xsd:element>

Problem

Is there a way to prevent empty elements of the form `<myElement/>` being used in your xml? In other words, can you specify in your xsd that `<myElement/>` is invalid? Using `nillable="false"` doesn't work, nor does `minOccurs="1"` - both of those allow `<myElement/>`.

Original source