chernevik
chernevik

Reputation: 4000

Write XSD to work without namespacing in target XML

How do I revise this XSD schema so it validates an XML file without a namespace declaration in that XML?

The schema does validate when there the candidate XML includes a declaration of the same namespace, but obviously the workflow is easier if I don't have to first edit the candidate documents.

I'm sure I'm missing something simple here, but an hour's guessing hasn't turned the trick.

The schema -- data.xsd

<schema
  xmlns=xsd:"http://www.w3.org/2001/XMLSchema"
  xmlns:target="http://myurl.com/response"
  targetNamespace="http://myurl.com/response"
  elementFormDefault="qualified">
  <xsd:element name="response">
    <xsd:complexType mixed="true" name="response">
      <xsd:all>
        <xsd:element name="item">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:any namespace="##any"
                   processContents="lax"
                   minOccurs="0"
                   maxOccurs="unbounded" /xsd:>
            </xsd:sequence>
          </xsd:complexType>
        </xsd:element>
        <xsd:element name="activities" >
          <xsd:complexType>
            <xsd:sequence>
              <xsd:any namespace="##any"
                   processContents="lax"
                   minOccurs="0"
                   maxOccurs="unbounded" /xsd:>
            </xsd:sequence>
          </xsd:complexType>
        </xsd:element>
        <!-- et cetera -->
      </xsd:all>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

This document validates -- data.namespaced.xml

<?xml version="1.0" encoding="utf-8"?>
<response
  xmlns="http://myurl.com/response"
  >
  <item>
    <! -- valid stuff -->
  </item>
  <activities>
    <! -- valid stuff -->
  </activities>
</response>

This document doesn't -- data.xml

<?xml version="1.0" encoding="utf-8"?>
<response>
  <item>
    <! -- valid stuff -->
  </item>
  <activities>
    <! -- valid stuff -->
  </activities>
</response>

I am using xmlllint for this:

xmllint --noout --schema data.xsd data.[namespaced.].xml

Thanks in advance.

Upvotes: 0

Views: 47

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122414

Remove the targetNamespace attribute from the xsd:schema. You could then also remove the elementFormDefault as it makes no difference when there's no target namespace.

In your original schema with the targetNamespace a declaration like

<xsd:element name="response">

declares an element whose local name is response and whose namespace URI is http://myurl.com/response. The namespace URI is an integral part of the element's fully qualified name, so the schema will not validate an element with the same local name but a different (or empty) namespace.

Conversely, if you remove the target namespace then the schema will validate non-namespaced documents but will not validate namespaced ones.

Upvotes: 1

Related Questions