HomeXML Page 6 - Doing More With XML Schemas (part 2)
Going Local - XML
In this second part, find out how to derive new element types by constraining existing ones, control access to your schema definitions, and redefine externally-provided schemas in place.
You'll remember, from the first article in this series, that the XML Schema specification allows you to split up schema definitions across multiple files, and include one file within another using the <xsd:include> element. This not only helps in logically separating base and derived definitions, it also makes your code cleaner and easier to maintain.
In case you're using a schema published by an external party, it's quite possible that you may need to make changes to it in order to tailor it to your specific requirements. Making changes to the original schema definitions is not always the best way to accomplish this task; sometimes, it's more logical to leave the original schema definitions as is, and simply over-ride them with new definitions where needed.
The XML Schema specification allows you to do this via the <xsd:redefine> element, which makes it possible to easily redefine an existing schema definition. In order to illustrate this, let's return to the last example in the first part of this article, in which I split up my schema definitions into "base-defs.xsd", which contained the base definitions,
Now, let's assume I wanted to redefine the new "JediMaster" type included in
"derived-defs.xsd" to include one more attribute. I could put this (re)definition in a file called "local-defs.xsd",
and reference this new file in my XML document instance.
<?xml version="1.0" encoding="UTF-8"?>
<gallery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="local-defs.xsd">
<character
xsi:type="JediMaster">
<name>Luke Skywalker</name>
<species>Human</species>
<language>Basic</language>
<home>Tatooine</home>
<gender>Male</gender>
<midichlorian-count>38000</midichlorian-count>
<weapon>lightsaber</weapon>
</character>
...
and so on ...
</gallery>
The XML validator will now use the new definition of the "JediMaster" class when
validating this document instance, rather than the original definition in "local-defs.xsd". Other types may be redefined in a similar manner.
This ability to selectively redefine schema elements makes it possible to easily "localize" an externally-provided set of schema definitions to specific needs, without damaging or altering the original.
And that's about it for the moment. In the next part of this article, I'll be looking at uniqueness, keys and references. Lotsa good stuff ahead - so make sure you tune in!
Note: All examples in this article have been tested on Linux/i586. Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article. YMMV!