Hello,
I’ve try to add your code in the functions.php file of my theme and it’s working perfectly.
If you have a SEO plugin, like Yoast SEO, sitemap is not generated by WordPress and your code will not have any effect.
You can try to deactivate WordPress sitemap using this code (from the same page as your code) and check if sitemap is still available.
add_filter( ‘wp_sitemaps_enabled’, ‘__return_false’ );
In my case the problem is due to access limitation to the WP API of the website.