Generate a sitemap with Java


This code dynamically generates a sitemap in Spring Boot

@RequestMapping(value = "/sitemap.xml", method = RequestMethod.GET, 
produces = MediaType.APPLICATION_XML_VALUE) 
    public XmlUrlSet main() { 
        XmlUrlSet xmlUrlSet = new XmlUrlSet(); 
        create(xmlUrlSet, "", XmlUrl.Priority.HIGH); 
        // List<String> containing with your urls 
                url -> create(xmlUrlSet, url, XmlUrl.Priority.MEDIUM)); 
        return xmlUrlSet; 
@XmlAccessorType(value = XmlAccessType.NONE) 
@XmlRootElement(name = "urlset", namespace = "") 
public class XmlUrlSet { 
    @XmlElements({@XmlElement(name = "url", type = XmlUrl.class)}) 
    private Collection<XmlUrl> xmlUrls = new ArrayList<>(); 
    public void addUrl(XmlUrl xmlUrl) { 
    public Collection<XmlUrl> getXmlUrls() { 
        return xmlUrls; 

Possible errors


No issues with Bing, it digest everything ;-)


The sitemap doesn't appear immediately in the results after the submission

The answer has to be MediaType.APPLICATION_XML_VALUE, if forgotten the xml will not be processed (http will answer with a json header) without any error message.

Error: Your Sitemap or Sitemap index file doesn't properly declare the namespace.

Google doesn't like if you have multiple namespaces`prefixes declared. ex.:

<ns2:urlset xmlns:ns2=""> 

To make Google happy add a to your package and add the followin line:

@javax.xml.bind.annotation.XmlSchema(namespace = "", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED, xmlns = { @javax.xml.bind.annotation.XmlNs(namespaceURI = "", prefix = "") }) 
package ... // your package 

This will remove the namespace from the xml file

Fullstack Angular / Java application quick start guide.
WebApp built by Marco using SpringBoot 3.2.4 and Java 21. Hosted in Switzerland (GE8).