xmlxsdnamespacesxml-namespaces

Defining XSD (XML Schema) type without a namespace but referring to it with namespace


Sorry if this question is a bit odd, but I'm new to XSD, and there's a snippet of XSD code I'm failing to understand. The code is below as the question is rather confusing without the code.

The XSD code defines a new Complex Type without a namespace (i.e. the default namespace), but an element definition uses the new type with a namespace. Is this allowed or as my present understanding of namespaces tells me it is not. I thought to use a type in a namespace it must be defined in the same namespace. But maybe if it's defined in the default namespace this is OK?

<schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://api.spp.org/schema/mui/Virtual/v2" xmlns:cmn="http://api.spp.org/schema/mui/Common/v4"
xmlns:vt="http://api.spp.org/schema/mui/Virtual/v2">

...

<element name="OfferByRange" type="vt:OfferByRangeType" />

<complexType name="OfferByRangeType">
    <sequence>
        <element name="UseSlope" type="boolean" maxOccurs="1" minOccurs="1" />
        <element maxOccurs="10" minOccurs="1" name="Point" type="cmn:MWPricePointType">
        </element>
    </sequence>
    <attributeGroup ref="vt:OfferByRangeIdGroup" />
</complexType>

<attributeGroup name="OfferByRangeIdGroup">
    <attribute name="locationName" type="cmn:LocationNameType" use="required" />
    <attribute name="startHour" type="cmn:DatetimeHourType" use="required" />
    <attribute name="stopHour" type="cmn:DatetimeHourType" use="required" />
</attributeGroup>

The line <element name="OfferByRange" type="vt:OfferByRangeType" /> refers to the type OfferByRangeType in the namespace vt. But the type is not defined in the namespace vt making me think this is not allowed? I'm just trying to understand XML namespaces better. Thanks!


Solution

  • The schema defines all elements in the target namespace. Which is defined in the schema tag. As you can see it is the same as the vt namespace. So not only is this correct. It is also the common way to do. Even though most people refer to the target namespace as tns.

    If you want to reference your own elements without a prefix (namespace), you can define the default namespace as target namespace like this:

    xmlns="http://api.spp.org/schema/mui/Virtual/v2"