Paneer Handi
Paneer Handi

Reputation: 115

How to add targetNamespace to XSD?

I want to use namespace in XML file. Current code working fine without a namespace using xsi:noNamespaceSchemaLocation.

(Working Code) test-document.xml:

<?xml version="1.1" encoding="UTF-8"?>
<root-element
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="./test-schema.xsd">
    <sizeElement>T1 T2 T1</sizeElement>
</root-element>

test-schema.xml:

<?xml version="1.1" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="root-element">
        <xs:complexType>
            <xs:all>
                <xs:element name="sizeElement" type="sizeList"/>
            </xs:all>
        </xs:complexType>
    </xs:element>
    <xs:simpleType name="size">
        <xs:restriction base="xs:token">
            <xs:enumeration value="T1"/>
            <xs:enumeration value="T2"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="sizeList">
        <xs:list itemType="size" />
    </xs:simpleType>
</xs:schema>

But when i try to add targettargetNamespace="ns" in <<xs:schema>> tag as attribute it showing error At:

<xs:list itemType="size" />

ERROR:

src-resolve: Cannot resolve the name 'size' to a(n) 'type definition' component.xsd(src-resolve)

I am using vs-code.

Upvotes: 1

Views: 1745

Answers (1)

kjhughes
kjhughes

Reputation: 111726

There are multiple concepts involved with validating XML in a namespace:

Here are the above concepts applied to your XML and XSD:

XML

<?xml version="1.0" encoding="UTF-8"?>
<root-element
    xmlns="http://example.com/ns"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://example.com/ns test-schema.xsd">
    <sizeElement>T1 T2 T1</sizeElement>
</root-element>

XSD

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified"
           xmlns="http://example.com/ns"
           targetNamespace="http://example.com/ns">
  <xs:element name="root-element">
    <xs:complexType>
      <xs:all>
        <xs:element name="sizeElement" type="sizeList"/>
      </xs:all>
    </xs:complexType>
  </xs:element>
  <xs:simpleType name="size">
    <xs:restriction base="xs:token">
      <xs:enumeration value="T1"/>
      <xs:enumeration value="T2"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="sizeList">
    <xs:list itemType="size" />
  </xs:simpleType>
</xs:schema>

The above XML is valid against the above XSD.

Upvotes: 1

Related Questions