0

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?

mkjp2011
  • 1
  • 1
  • #1 What is the problem? the `\"` after xmlns? #2 Try with some client like postman or curl to detect what is the response and headers of your /sitemap – JRichardsz Nov 23 '21 at 19:38
  • @JRichardsz - The problem is that the response is encapsulating the XML in double quotes. This breaks the browser when trying to render the XML contents. In postman I see the following: content-type application/xml; charset=utf-8 content-length 195 – mkjp2011 Nov 23 '21 at 19:44
  • What framework are you using? I see: `@Get() public getSitemapFile()`. On pure express, it is easy return a xml. – JRichardsz Nov 23 '21 at 19:50
  • @JRichardsz - Using NodeJS/Express and tsoa to serve documentation – mkjp2011 Nov 23 '21 at 19:53

0 Answers0