# Fix XML namespace mismatches without guessing

Source: https://xsdhub.com/learn/xml-namespaces-explained

Understand xmlns, prefixes, targetNamespace and elementFormDefault with a complete XML/XSD pair and a practical namespace debugging checklist.

## Compare the full name, not just the tag

If a validator cannot find a declaration for stock, changing its spelling may not help. An XML element is identified by its namespace URI together with its local name. First compare those two pieces with the root declaration in the schema. Prefixes are shorthand; two prefixes bound to the same URI can refer to the same element.

## A matching document

Here the default namespace applies to stock and its unprefixed child sku. The unprefixed warehouse attribute has no namespace. That difference is deliberate: a default element namespace does not automatically qualify unprefixed attributes.

```xml
<stock xmlns="urn:example:stock" warehouse="North">
  <sku>BK-204</sku>
</stock>
```

## The matching schema

targetNamespace supplies the vocabulary URI. elementFormDefault="qualified" requires locally declared elements such as sku to use that namespace too. The warehouse attribute remains unqualified under the default attribute rules. Copy both examples into the validator to check the complete pair.

```xml
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
  targetNamespace="urn:example:stock"
  elementFormDefault="qualified">
  <xs:element name="stock">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="sku" type="xs:string"/>
      </xs:sequence>
      <xs:attribute name="warehouse" type="xs:string"/>
    </xs:complexType>
  </xs:element>
</xs:schema>
```

## A prefix is optional, the URI is not

The document could instead use s:stock and s:sku with xmlns:s="urn:example:stock". Both elements would have the same expanded names as before. Renaming only the prefix will not repair a wrong URI. Treat namespace names as exact identifiers: a trailing slash or a change in letter case can produce a different name. A namespace URI does not have to be a downloadable schema.

## When only the child element fails

Check elementFormDefault and any local form override. A schema with unqualified local elements may expect a qualified root but children without a namespace. In a document that uses a default namespace, xmlns="" can reset it for a subtree. Do not add that reset everywhere: use it only when the schema requires unqualified elements.

## A focused debugging sequence

Check the root namespace, the schema targetNamespace, local element qualification and attribute qualification in that order. Then confirm the schema version. Keep namespace declarations when formatting or copying fragments: moving a fragment outside its original scope can change its meaning or leave a prefix unbound.

## Primary references

- [W3C Namespaces in XML](https://www.w3.org/TR/xml-names/)
- [W3C XML Schema primer](https://www.w3.org/TR/xmlschema-0/)
