Ian F.
Ian F.

Reputation: 43

How to define namespace for xsd:element to override default targetNamespace

I'm attempting to validate xml against a xsd schema, rather than using Serialization into Java types derived from our WSDL file using WSDL to Java.

Our outermost element tags are defined in the WSDL, but we need to validate against the xsd schema, so we're attempting to add outermost element tags to the xsd. However when the outermost wrapper includes a namespace which differs from the targetNamespace of the xsd file, the xml fails validation.

Simplified xml

<ns6:responseWrapper
  xmlns="http://somewhere.com/types/2016/A"
  xmlns:ns6="http://somewhere.com/operations/2016/A"
>
  <user>
    <id>the_id</id>
    <someInfo>the_source</someInfo>
  </user>
</ns6:responseWrapper>

Simplified Schema

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xsd:schema
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:tns="http://somewhere.com/types/2016/A"
  targetNamespace="http://somewhere.com/types/2016/A"
  elementFormDefault="qualified"
>
  <xsd:element
    xmlns:ns6="http://somewhere.com/operations/2016/A"
    name="responseWrapper"
    type="tns:ResponseWrapper"
  />

  <xsd:complexType name="ResponseWrapper">
    <xsd:element name="user" type="tns:User"/>
  </xsd:complexType>

  <xsd:complexType name="User">
    <xsd:sequence>
      <xsd:element name="id" type="xsd:string"/>
      <xsd:element name="someInfo" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>

</xsd:schema>

The xml and schema above generate Cannot find the declaration of element 'ns6:responseWrapper` errors.

I'd like to modify the schema so that the xml validates successfully.

Upvotes: 0

Views: 1993

Answers (1)

Michael Kay
Michael Kay

Reputation: 163595

In general, if you have elements in two different namespaces, you need to define them in different XSD schema documents linked by xs:import.

There's a limited exception in XSD 1.1 that allows you to use a targetNamespace attribute on a local element declaration, but it has so many restrictions that I don't think it's often used.

Putting an extra namespace declaration like xmlns:ns6="http://somewhere.com/operations/2016/A" on an xs:element declaration is perfectly legal but has absolutely no effect on the meaning of the schema, unless the ns6 prefix is actually used somewhere on a QName.

Upvotes: 1

Related Questions