11

I found some tips for this problem, but still didn't help me.

Here is my XML

<?xml version="1.0" encoding="UTF-8"?>
<work xmlns="http://www.w3.org/2001/XMLSchema"
      xmlns:tns="http://www.w3.org/2001/XMLSchema-instance"
      tns:schemaLocation="myXSDSchema.xsd">
  <tns:Objects>
    <tns:Object Name=":" Location=":">
    </tns:Object>
  </tns:Objects>
</work>

Here is my XSD file:

<schema xmlns="http://www.w3.org/2001/XMLSchema" 
        xmlns:tns = "http://www.w3.org/2001/XMLSchema" 
        elementFormDefault="qualified">
  (some checks)
</schema>

My XSD file is located in the same folder as the XML.

How to link these 2 files?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
porandddr
  • 129
  • 1
  • 1
  • 6

1 Answers1

19

How to link an XSD to an XML document depends upon whether the XML document is using namespaces or not...

Without namespaces

Use xsi:noNamespaceSchemaLocation to provide a hint as to the XSD to be used:

  • XML

    <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="example.xsd">
      <!-- ... -->
    </root>
    
  • XSD

    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:element name="root">
        <!-- ... -->
      </xsd:element>
    </xsd:schema>
    

With namespaces

Use xsi:schemaLocation to provide a hint as to the XSD to be used:

  • XML

    <ns:root xmlns:ns="http://example.com/ns"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://example.com/ns example-ns.xsd">
      <!-- ... -->
    </ns:root>
    
  • XSD

    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                targetNamespace="http://example.com/ns">
      <xsd:element name="root">
        <!-- ... -->
      </xsd:element>
    </xsd:schema>
    
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • without namespace, is it the same syntax to specify an `xsd` on the local file system? – Thufir Jan 13 '19 at 03:43
  • 1
    Yes, XSD syntax is the same for local or remote; both are URLs. If you're having trouble specifying a local URL, see [How to reference a local XML Schema file correctly?](https://stackoverflow.com/q/19253402/290085) – kjhughes Jan 13 '19 at 03:56
  • @kjhughes in practice you can use `xsi:noNamespaceSchemaLocation` attribute to reference an XML Schema document that does have a target namespace. – user7233170 Mar 29 '22 at 06:17
  • 1
    @user7233170: What more are you trying to say beyond that which this answer already says? – kjhughes Mar 29 '22 at 15:05