Sub topic 9
Anatomy of a sitemap file
This chapter covers the structure of an XML sitemap: the elements, the namespace, encoding rules, and the mistakes that make a crawler reject a file. It assumes you can read basic XML and know what a URL and an HTTP status code are. Fields like lastmod, size limits, and sitemap index files get their own chapters, so they appear here only briefly.
What a sitemap file is
An XML sitemap is a UTF-8 encoded XML document that lists URLs you want search engines to discover. The format is defined by the Sitemaps protocol at sitemaps.org. Google, Bing, and other major engines read it.
A sitemap is a hint, not a command. A listed URL may still go uncrawled or unindexed. A URL missing from the sitemap can still be found through links. The sitemap's job is to make discovery faster and more complete.
The minimal structure
Every sitemap has three nested layers:
urlsetis the root element. It wraps the whole file.urlis one entry for each page. It appears once per listed URL.locis the child ofurlthat holds the page's absolute URL.
Here is a complete sitemap that uses only the required elements, plus an XML declaration:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://www.example.com/</loc>
</url>
<url>
<loc>https://www.example.com/blog/first-post</loc>
</url>
</urlset>Only urlset, url, and loc are required. The optional lastmod element can sit beside loc inside each url.
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://www.example.com/</loc>
<lastmod>2026-11-01</lastmod>
</url>
<url>
<loc>https://www.example.com/blog/first-post</loc>
<lastmod>2026-10-15T09:30:00+00:00</lastmod>
</url>
</urlset>The namespace
The attribute xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" declares the XML namespace. A namespace is a label that tells a parser which vocabulary the element names belong to. Here it says that urlset, url, and loc follow the Sitemaps protocol, version 0.9.
Common namespace errors:
- Leaving the attribute out. A strict parser may see elements with no vocabulary and reject the file.
- Typing
httpsinstead ofhttp. The namespace is an identifier, not a link. It must match the string exactly, and it useshttp. - Changing the version number. The protocol is still at 0.9.
Rules for the loc element
loc is the part most likely to cause trouble. These rules apply to every entry:
- Absolute URL. Include the scheme and host, such as
https://www.example.com/page. A relative path like/pageis invalid. - Same host and protocol. A sitemap may list only URLs on the host where the sitemap is located, with the same scheme. A sitemap at
https://www.example.com/should not listhttp://www.example.com/orhttps://blog.example.com/URLs. Cross-host listing is possible only with extra steps, such as submitting through Search Console or referencing the sitemap from the other host's robots.txt. - Canonical form. List the exact URL you want indexed. If the page has a canonical URL (the preferred address for duplicate pages), list that one. Do not list the same page under several URL variants.
- Length. A URL must be shorter than 2,048 characters.
- Escaping. The URL must be XML-escaped, and non-ASCII characters should be percent-encoded.
Escaping special characters
Five characters have special meaning in XML and must be written as entities inside loc:
| Character | Entity |
|---|---|
| `&` | `&` |
| `'` | `'` |
| `"` | `"` |
| `>` | `>` |
| `<` | `<` |
The ampersand is the one you meet most often, in query strings. The URL https://www.example.com/list?page=2&sort=asc becomes:
<loc>https://www.example.com/list?page=2&sort=asc</loc>An unescaped & makes the whole file malformed XML. A crawler that hits a parse error may ignore everything after it, or the entire file.
Non-ASCII characters in a path, such as /café, should be percent-encoded as UTF-8 (/caf%C3%A9). The file itself is UTF-8, but percent-encoding keeps the URL unambiguous.
What belongs in the file
The sitemap should list URLs that you want indexed and that a crawler can actually index. In practice, each listed URL should:
- Return HTTP 200, not a redirect (3xx), a not-found (404), or a server error (5xx).
- Be allowed by robots.txt. Listing a URL you have disallowed sends a contradictory signal.
- Not carry a
noindexdirective. - Be the canonical version of its content.
A sitemap full of redirected, blocked, or noindexed URLs wastes crawl attention. It also makes the sitemap a poor guide to your site, because crawlers learn to trust it less. Treat the file as a curated list of your index-worthy pages, not a dump of every URL the site can produce.
Encoding and file naming
Save the file as UTF-8. The declaration <?xml version="1.0" encoding="UTF-8"?> should be the first thing in the file, with no blank line or space before it. A leading space or a byte-order mark added by the wrong editor setting can cause parse errors in some tools.
Name the file whatever you like, but use the .xml extension, for example sitemap.xml. A sitemap may also be gzip-compressed (sitemap.xml.gz) to save bandwidth. The size limits apply to the uncompressed content.
The file's location matters. A sitemap can list only URLs at or below its own directory path unless you take extra steps. A sitemap at https://www.example.com/blog/sitemap.xml may list /blog/... URLs, but not /shop/... URLs. Putting the file at the site root, https://www.example.com/sitemap.xml, avoids this limit.
Optional fields you will see
The protocol defines two more optional elements, changefreq and priority. Major search engines such as Google ignore them, so do not spend time tuning them. A later chapter explains this, along with how to keep lastmod honest. Extension namespaces for images, video, news, and hreflang alternates also build on this same skeleton.
Building the file from code
Writing XML by hand fails once the site has more than a few pages. Generating it with a real XML library has a second benefit: the library escapes special characters for you.
import xml.etree.ElementTree as ET
NS = "http://www.sitemaps.org/schemas/sitemap/0.9"
ET.register_namespace("", NS)
def build_sitemap(pages, path):
urlset = ET.Element(f"{{{NS}}}urlset")
for loc, lastmod in pages:
url = ET.SubElement(urlset, f"{{{NS}}}url")
ET.SubElement(url, f"{{{NS}}}loc").text = loc
ET.SubElement(url, f"{{{NS}}}lastmod").text = lastmod
ET.ElementTree(urlset).write(path, encoding="utf-8", xml_declaration=True)
build_sitemap(
[
("https://www.example.com/", "2026-11-01"),
("https://www.example.com/about", "2026-09-12"),
],
"sitemap.xml",
)Three details in this script matter:
register_namespace("", NS)makes the namespace the default, so the output reads<urlset xmlns="...">and not<ns0:urlset ...>. Both forms are valid XML, but the default form is what most people expect.- Each element name is written as
{namespace}name. This is how ElementTree attaches an element to a namespace. - Setting
.textonlocescapes&and<automatically. Do not pre-escape the string yourself, or you will get&amp;.
The script writes the declaration with single quotes (<?xml version='1.0' encoding='utf-8'?>). That is valid XML and crawlers accept it.
Common structural mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Missing or wrong namespace | File may be rejected or elements ignored | Use the exact `http://www.sitemaps.org/schemas/sitemap/0.9` value |
| Relative URL in `loc` | Entry invalid | Use the full `https://host/path` form |
| Unescaped `&` | Malformed XML, parse error | Write `&`, or use an XML library |
| Mixed hosts or schemes | URLs ignored or flagged | Keep one host and scheme per sitemap |
| Listing redirects or 404s | Wasted crawl effort, warnings in reports | List only final, 200-status URLs |
| Whitespace before the XML declaration | Parse error in strict readers | Start the file with `<?xml` |
| HTML returned at the sitemap URL | Sitemap unreadable | Serve XML with a 200 status |
Checking a file quickly
Before you submit a sitemap, confirm that it is well-formed XML and that the declared namespace is right. This short script parses a file and prints the root tag and the number of entries:
import xml.etree.ElementTree as ET
NS = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}
tree = ET.parse("sitemap.xml")
root = tree.getroot()
print(root.tag)
locs = [e.text for e in root.findall("sm:url/sm:loc", NS)]
print(len(locs), "URLs")
for loc in locs:
if not loc.startswith(("http://", "https://")):
print("Not absolute:", loc)If the file is malformed, ET.parse raises a ParseError that names the line and column. If the namespace is wrong, the root tag will not start with {http://www.sitemaps.org/schemas/sitemap/0.9} and locs will be empty.
Exercise
A sitemap entry reads <loc>https://www.example.com/shop?cat=shoes&color=red</loc>. A crawler reports the file as unparseable. What is wrong, and how do you fix it? Name one more check you should make on this URL before keeping it in the sitemap.
Show answer
The unescaped & makes the XML malformed. Write it as &: <loc>https://www.example.com/shop?cat=shoes&color=red</loc>. Better still, build the file with an XML library so escaping is automatic. Then check that the URL returns HTTP 200, is allowed by robots.txt, has no noindex, and is the canonical version. Filter-style URLs like this are often duplicates of a category page and may not belong in the sitemap at all.
Exercise
You place a sitemap at https://www.example.com/blog/sitemap.xml and list https://www.example.com/shop/boots in it. Why is this a problem, and what is the simplest fix?
Show answer
A sitemap can normally list only URLs at or below the directory where it lives, so the /shop/ URL falls outside the allowed scope and may be ignored. The simplest fix is to move the sitemap to the site root (https://www.example.com/sitemap.xml), where it can cover every path on the host.