Xsd empty element constraint

Is there a way to prevent the use of empty elements of the <myElement/> form in your xml? In other words, can you indicate in xsd that <myElement/> is not valid?

Using nillable="false" does not work, and minOccurs="1" - both of them allow <myElement/> .

+6
xml validation xsd
source share
2 answers

If you are trying to prevent an element from appearing, you can mark it with minOccurs="0" . I assume that this is not what you need, so if you are trying to make sure that there are always attributes associated with a complex element, then you should indicate at least one of the attributes usage="required" or use a group of attributes. If myElement is a simple type and you want to make sure that it matters, you can always restrict its type. If you need a nonzero string, you can do the following:

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

If your schema check cannot show an error when the DATE element of the data type is NULL, you can use the template [if you do not need to enter the required format];

I added an example, the implementation of such code will work on your tool,

This is an XML example:

 <root> <date1>12/31/1999</date1> <!-- The Date format defined here is MM/DD/YYYY, null value or Date with any other format aren't accepted--> </root> 

This is the corresponding XSD:

 <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:include schemaLocation="Date_Def.xsd"/> <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element name="date1" type="DATE_TYPE" minOccurs="0" maxOccurs="1" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> 

Note that I am including another schema file that includes a definition of type DATE_TYPE,
Here is the Date_Def.xsd file:

 <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="DATE_TYPE"> <xs:restriction base="xs:string"> <xs:pattern value="([0][1-9]|[1][0-2])/([0][1-9]|[1-2][0-9]|[3][0-1])/[1-2][0-9][0-9][0-9]"/> </xs:restriction> </xs:simpleType> </xs:schema> 

The date format specified here is MM / DD / YYYY, null or Date with any other format is not accepted. If you want to accept also a null tag, replace the template with this.

 <xs:pattern value="|(([0][1-9]|[1][0-2])/([0][1-9]|[1-2][0-9]|[3][0-1])/[1-2][0-9][0-9][0-9])"/> 

Checking what accepts is either a null tag or a date-value for the template MM / DD / YYYY.

If you need more help on template design, then feel free to do it in SO, hope this helps. :-)

[note :: Definition type can also be defined in a single file, which requires additional namespaces mentioned in XML, as well as XSD files that define the external file is harmless and reused]

+4
source share

All Articles