Andrew No
Andrew No

Reputation: 535

Explanation/example of the proper use of an XML Schema?

I am beyond confused with XML Schemas. I believe they are used to define custom elements to be used as a template.

Say I have the following schema:

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <!-- definition of simple elements -->
  <xs:element name="text" type="xs:string"/>

  <!-- definition of attributes -->
  <xs:attribute name="choice_value" type="xs:int"/>

  <!-- definition of complex elements -->
  <xs:element name="choice">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="text" minOccurs="1"/>
        </xs:sequence>
        <xs:attribute ref="choice_value" use="required"/>
    </xs:complexType>
  </xs:element>

</xs:schema>

Can someone please provide a detailed example, a complete one element XML file on how I use and import this schema? I am able to import or include it, when I try to declare my element, it says and can't be found. Google results only show one how to import, but not actually apply it.

Upvotes: 0

Views: 989

Answers (1)

kjhughes
kjhughes

Reputation: 111491

An XML Schema defines an XML vocabulary (what element and attribute names may be used) and grammar (how elements and attributes may be composed).

Per your XSD, the following XML documents, for example, would be valid:

  1. <text/>
  2. <text>asdf</text>
  3. <choice choice_value="1"><text/></choice>
  4. <choice choice_value="1"><text>asdf</text></choice>

Association of an XML document with an XML Schema is often done via xsi:noNamespaceSchemaLocation or xsi:schemaLocation attributes on the root element. Here is an example of how to hint to the XML processor that the XML Schema to use to validate XML document #4 above is try.xsd:

<choice choice_value="1"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="try.xsd">
    <text>asdf</text>
</choice>

Be aware that there are other mechanisms to associate an XSD with an XML document such as XML Catalogs, or command line or GUI-set preferences particular to any given XML processor.

Upvotes: 1

Related Questions