I have a requirement to provide an endpoint that generates a sitemap.
This endpoint uses 'xmlbuilder2' and the goal is to return pure XML that can be delivered to the browser.
@Get()
public getSitemapFile(): Promise<any> {
return new Promise<any>((resolve, reject) => {
const root: SiteMapRoot = {
xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9'
};
const urlset = create().ele(root.xmlns, 'urlset');
// urlset.com('Testing things out -- building out items');
const newUrl: SiteMapDetail = {
loc: 'https://testsitemapurl.com/',
lastmod: new Date(),
changefreq: 'daily'
};
urlset
.ele('url')
.ele('loc')
.txt(newUrl.loc).up()
.ele('lastmod')
.txt(newUrl.lastmod.toISOString()).up()
.ele('changefreq')
.txt(newUrl.changefreq).up();
const resultXml = urlset.end({ prettyPrint: true });
console.log(resultXml);
this.setHeader('Content-Type', 'application/xml');
resolve(urlset.toString());
});
}
The expected response would be something like this:
<?xml version="1.0"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://testsitemapurl.com/</loc>
<lastmod>2021-11-23T19:15:10.834Z</lastmod>
<changefreq>daily</changefreq>
</url>
</urlset>
However, receiving the following as the response:
"<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">
<url>
<loc>https://testsitemapurl.com/</loc>
<lastmod>2021-11-23T19:15:10.834Z</lastmod>
<changefreq>daily</changefreq>
</url>
</urlset>"
What is tripping me up is:
- The return type is set to XML
- The return of the XML object is string
- This explains why I receive the XML string value in quotes as the response
Is there something I am doing wrong (obviously there is)? Is there a different utility I can use?