tags:

views:

34

answers:

3

When you add an xml schema to a document like I understand that the xmlns is not actually the location of the xsd file. Is this correct?

  • How do you in practice reference an xml file's schema?
  • Is it usually on a web server? That would seem very chatty.
  • Is it referenced by relative path?
  • Is it not actually referenced in the xml but rather loaded into an xml parser arbitrarily?

Any feedback?

A: 

The xmlns references a namespace URI, which is the symbolic name for the schema. It is up to the XML parser to resolve these namespace URIs against an actual schema instance. Some XML documents will give it a hint in the form of a schemaLocation, which should be the URL of an actual schema file, but the parser is free to ignore this.

Best practice would be for the parsing application to have a local (or perhaps cached) copy of the schema it needs, and for it to use a schema catalogue to resolve namespace URIs against those locally-held schema.

skaffman
+1  A: 

Example from Spring:

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
  default-lazy-init="true">
</beans>

The xsi:schemaLocation maps namespace URIs to actual locations of schemata.

Then, typical parsing environments use a Resolver to map these to a local copy.

bmargulies
+1  A: 

You have a schema with a target namespace and qualified elements (wich means you don't have to prefix your elements to apply target namespace):

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
        targetNamespace="http://www.exemple.com/my-namespace-URI"
        xmlns="http://www.exemple.com/my-namespace-URI"
        elementFormDefault="qualified">
    <-- Your schema definition -->
</xs:schema>

You have to include it in your root element. First the xml-schema namespace:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

(from here the xsi: prefix corresponds to this namespace)

Then reference the schemaLocation attribute

xsi:schemaLocation="http://www.exemple.com/my-namespace-URI my.xsd"

where my.xsd is the location of the XSD file (by default relative to the XML document's location). You can put a complete URL like

xsi:schemaLocation="http://www.exemple.com/my-namespace-URI http://www.exemple.org/xml/my.xsd"

So that gives your document:

<?xml version="1.0"?>
<doc xmlns="http://www.exemple.com/my-namespace-URI"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.exemple.com/my-namespace-URI http://www.exemple.org/xml/my.xsd"&gt;
    <!-- Document content -->
</doc>

Note that the XSD file URL is not necessarily related to the namespace URI.

streetpc