I'm new to XSD, and I'm quite confused as to when to use attribute, and when to use element?
Why cant we specify minOccurs and maxOccurs in attribute?
Also, why is it we cannot specify use="required" in element?
An element is an XML node - and it can contain other nodes, or attributes. It can be a simple type or a complex type. It is an XML entity. An attribute is a descriptor.
An attribute provides extra information within an element. Attributes are defined within an XSD as follows, having name and type properties. An Attribute can appear 0 or 1 times within a given element in the XML document. Attributes are either optional or mandatory (by default the are optional).
Attribute represents the attribute of an XML element. XSD defines it as a simple type.
Attributes are part of XML elements. An element can have multiple unique attributes. Attribute gives more information about XML elements. To be more precise, they define properties of elements. An XML attribute is always a name-value pair.
An element is an XML element - a opening tag, some content, a closing tag - they are the building blocks of your XML document:
<test>someValue</test>
Here, "test" would be an element.
Attributes is an additional info on a tag - it's an "add-on" or an extra info on an element, but can never exist alone:
<test id="5">somevalue</test>
"id" is an attribute.
You cannot have multiple attributes of the same name on a single tag --> minOccurs/maxOccurs makes no sense. You can define required (or not) for an attribute - anything else doesn't make sense.
The elements are defined by their occurrence inside complex types - e.g. if you have a complex type with a <xs:sequence>
inside - you are defining that all elements must be present and must the in this particular order:
<xs:complexType name="SomeType">
<xs:sequence>
<xs:element name="Element1" type="xs:string" />
<xs:element name="Element2" type="xs:string" />
</xs:sequence>
</xs:complexType>
Inside an element of that type, the sub-elements "Element1" and "Element2" are required and must appear in this order - there's no need for "required" or not (like with attributes). Whether or not an element is required is defined by the use of minOccurs and maxOccurs; both are =1 by default, e.g. the element must occur, and can only occur once. By tweaking those settings, you can define an element to be optional (minOccurs=0), or allow it to show up several times (maxOccurs > 1).
I'd strongly recommend you check out the W3Schools Tutorial on XML Schema and learn some more about XML schema.
Marc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With