V9: How to generate sitemap.xml programmatically?

How can I generate a sitemap.xml programmatically where I need to add my own stuff there, e.g. dynamic page routes which don’t exist as pages in Concrete sense.

Can I start the core Generate Sitemap task programmatically to generate the sitemap.xml and when it’s done I can simply add the dynamic “pages” to the generated sitemap file?

Does Concrere have its own library for working with XML?

Don’t have any recent experience myself messing with this but I believe this looks like a good place to start… Concrete\Core\Page\Sitemap | ConcreteCMS API

I’ve done this in a v8 Project. - It’s not very difficult and probably still works similarly in v9.

As you might know, there is a Default Automated Job that creates the sitemap.xml based on all of your “normal” Concrete CMS Content.

If you want manipulate or add to that, you can use Event Listeners on Events fired by the Core to do that:

Events::addListener('on_sitemap_xml_ready', array($this, 'modifySitemap'));

function modifySitemap(){
    $xmlDoc = $event->getDocument();
    $xmlDoc->addAttribute('xml','Custom XML Attributes as you Desire');
    $event->setDocument($xmlDoc);
}

$xmlDoc is a PHP SimpleXML Object and can be modified as such:
Custom XML Attributes

The problem with that approach is that you don’t know in which mode that runs and in the lowmemory mode the event is not fired:

https://documentation.concretecms.org/api/9.0.1/Concrete/Core/Page/Sitemap/SitemapWriter.html

What I’ve done is I simply check the sitemap.xml exists and append url nodes to it. If it doesn’t exist, the sitemap has to be generated and then updated. No big deal - 2 steps instead of 1.