Create a Sitemap XML: Generate, Validate and Submit
Create sitemap XML from approved URLs, run a local example, check canonical and indexing conflicts, and troubleshoot submission errors.
Updated · Markdown version
An AI agent can help create a sitemap XML file, but it cannot decide which pages deserve indexing from a list of addresses alone. Start with approved canonical URLs, generate the file, compare its contents with the input, then verify the deployed file and Search Console result. A valid sitemap helps discovery; it does not guarantee indexing or rankings.
Choose the simplest way to create your sitemap
If your CMS already maintains a sitemap, use that as the starting point. Repair its URL selection or configuration instead of publishing a competing list that becomes stale. A small static site can use the reproducible example below. A large or frequently changing site should generate the file from its content database or build process.
For ordinary page URLs, Google also accepts a plain text sitemap. Choose XML when your implementation needs its structure or supported extensions. This example covers page URLs only, without image, video or language extensions. Google explains the supported formats.
Prepare a URL list that reflects the live site
You need Python 3, an approved HTTPS production origin and a UTF-8 text file with one absolute URL per line. Work in a new local folder. Use synthetic data while learning; do not send private URL exports to an external AI service without authorization.
For your real list, inspect status, canonical, indexing directives and access restrictions. Keep the production URLs you want indexed. Investigate redirects, errors, alternate hosts, staging addresses and duplicates. A page returning HTTP 200 may still have a noindex directive or canonical pointing elsewhere. URL syntax validation cannot discover those facts.
Save this synthetic example as urls.txt:
https://example.com/guides/
https://example.com/guides/install/
https://example.com/catalog/?category=data&sort=nameThe parameterized URL demonstrates escaping, not a recommendation to index filter or sort combinations. Include a query URL in your real sitemap only when it is an intended canonical page. Do not lowercase paths, strip parameters or add trailing slashes automatically; confirm the site's actual canonical policy.
Create the sitemap without inventing URLs
Give an agent this bounded request:
Create a root-level sitemap.xml only from my approved URLs.
Use the production origin I provide. Preserve every approved URL exactly.
Do not crawl, add guessed pages, change canonical settings or submit anything.
Generate UTF-8 XML with the sitemap namespace. Omit lastmod because I have
not supplied verified page-modification dates. Compare the parsed output
against the input and report errors rather than silently repairing URLs.Save the following as build_sitemap.py. It builds a single root-level HTTPS sitemap, escapes XML through the serializer and refuses to replace an existing output file. It is a small offline example, not a crawler or comprehensive URL validator.
"""Small root-level HTTPS sitemap from an explicitly approved URL list. Offline."""
import json
import re
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
from urllib.parse import urlsplit
def build(source, origin):
base = urlsplit(origin)
if base.scheme != 'https' or not base.netloc or base.path not in ('', '/') or base.query or base.fragment or base.username or base.password:
raise ValueError('origin must be an HTTPS origin such as https://example.com')
with open(source, 'rb') as stream:
raw = stream.read(8 * 1024 * 1024 + 1)
if len(raw) > 8 * 1024 * 1024:
raise ValueError('example input cap is 8 MiB; use your CMS pipeline for larger exports')
urls = [s.strip() for s in raw.decode('utf-8-sig').splitlines() if s.strip()]
if not 1 <= len(urls) <= 50000:
raise ValueError('expected 1 to 50000 URLs')
if len(set(urls)) != len(urls):
raise ValueError('duplicate URL; review input instead of silently dropping rows')
namespace = 'http://www.sitemaps.org/schemas/sitemap/0.9'
ET.register_namespace('', namespace)
root = ET.Element('{' + namespace + '}urlset')
for position, url in enumerate(urls, 1):
parsed = urlsplit(url)
if (not url.isascii() or any(ord(c) <= 32 or ord(c) == 127 for c in url)
or len(url) >= 2048 or parsed.scheme != 'https'
or parsed.netloc != base.netloc or parsed.fragment or parsed.username
or re.search(r'%(?![0-9A-Fa-f]{2})', url) or '\\' in url):
raise ValueError('URL validation failed at line ' + str(position))
item = ET.SubElement(root, '{' + namespace + '}url')
ET.SubElement(item, '{' + namespace + '}loc').text = url
payload = ET.tostring(root, encoding='utf-8', xml_declaration=True)
if len(payload) > 50 * 1024 * 1024:
raise ValueError('sitemap exceeds 50 MiB uncompressed; split it')
extracted = [x.text for x in ET.fromstring(payload).findall('{' + namespace + '}url/{' + namespace + '}loc')]
if extracted != urls:
raise ValueError('round-trip URL comparison failed')
return payload, len(urls)
def main():
try:
if len(sys.argv) != 4:
raise ValueError('usage: build_sitemap.py urls.txt https://example.com sitemap.xml')
payload, count = build(sys.argv[1], sys.argv[2])
with open(sys.argv[3], 'xb') as output:
output.write(payload)
print(json.dumps({'written': True, 'urls': count, 'bytes': len(payload), 'live_pages_checked': False}))
return 0
except (OSError, ValueError, UnicodeError) as exc:
print(json.dumps({'error': str(exc)}))
return 2
if __name__ == '__main__':
sys.exit(main())Run from that folder. On Windows PowerShell:
py -3 -I .\build_sitemap.py .\urls.txt https://example.com .\sitemap.xmlOn macOS or Linux:
python3 -I build_sitemap.py urls.txt https://example.com sitemap.xmlUse your installed Python command if py or python3 is unavailable. The expected summary reports three URLs and live_pages_checked: false. In the XML file, the last query separator appears as &; parsing it returns the original &. This is correct XML escaping, not a changed destination.
Verify the file and the pages separately
- File correctness: UTF-8 XML, sitemap namespace, one loc per approved URL, no duplicates, matching input/output URL order and count.
- Scope and limits: stay within 50,000 URLs and 50 MiB uncompressed per sitemap. Split larger exports and use a sitemap index. The teaching script also has an 8 MiB input cap; it is deliberately narrower than the protocol.
- Live page behavior: inspect every URL for a small list. For larger lists, automate status and canonical/directive checks and manually review important pages and exceptions. Record unverified rows instead of calling the whole list clean after a small sample.
- Dates: add lastmod only from a reliable record of significant page changes. A generation date is not a substitute. Google ignores priority and changefreq.
The sitemap protocol defines XML requirements and general location rules. Google's documentation adds an important qualification: absent submission through Search Console, a sitemap's directory restricts the descendants it affects. Hosting it at the root avoids this complication for the ordinary same-site workflow. Cross-site hosting and multi-host setups need their own verified configuration; this script does not implement them.
Publish only when the site is ready for indexing
After approval, have the site's normal deployment process serve the file at its root. This guide does not authorize a deployment or a change to a site's prelaunch noindex policy.
- Open the deployed sitemap URL and verify that it returns the XML, not a login page, HTML error or redirect to a preview host.
- Check its URLs against the deployed production origin again. A valid local file can become wrong if deployment substitutes staging addresses.
- Add the sitemap location to robots.txt or submit it in the verified site's Search Console Sitemaps report, using an account authorized for that property.
- Inspect processing status and reported errors. Then inspect a few important URLs to distinguish discovered, crawled and indexed states.
A successfully processed sitemap does not mean all URLs are indexed. Google describes sitemaps as a discovery aid and explains when a site may need one in its sitemap overview.
Fix common sitemap problems
| Symptom | Check | Next action |
|---|---|---|
| Script rejects an entry | Origin, fragment, duplicate or URL encoding | Correct the approved export; do not invent a replacement |
| XML parser rejects the file | Raw ampersands, broken tags, encoding | Regenerate with the XML serializer and re-compare URLs |
| Output already exists | The example deliberately prevents replacement | Inspect the existing file; use a different draft output name |
| Search Console cannot fetch it | Public response, host, permissions and error body | Fix delivery before resubmitting |
| Sitemap processed, page not indexed | Canonical, noindex, crawl restrictions and page quality | Investigate the page; repeated submission is not a diagnosis |
Continue with the right next step
Use technical-seo-audit for a repeatable audit workflow; read its scope and evaluation evidence before relying on it. If your URL inventory is JSON, convert JSON to CSV explains how to inspect records without hiding missing fields. For broader agent workflow basics, see how to use an AI agent.
Frequently asked questions
Can AI create a sitemap automatically?
It can draft code and transform an approved list. It still needs actual site data and independent checks. Do not accept guessed URLs or let a generated file stand in for a live indexing audit.
Does a sitemap guarantee Google indexing?
No. File processing, discovery, crawling and indexing are different outcomes. Use the relevant Search Console reports to identify which stage failed.
Do I need a video to complete this task?
The commands and expected result are available in text. A short walkthrough can help someone unfamiliar with creating files and running Python, but it must use the same example and include captions and a transcript. No video is required for the steps above.
Related skills in this catalog
Platform Score is our assessment under a published method. It is not a safety guarantee.
Related guides
Sources
- https://www.sitemaps.org/protocol.html (accessed 2026-11-25)
- https://developers.google.com/search/docs/crawling-indexing/sitemaps/build-sitemap (accessed 2026-11-25)
- https://developers.google.com/search/docs/crawling-indexing/sitemaps/overview (accessed 2026-11-25)