Skip to content

Commit 73b6e81

Browse files
committed
refactor: improve XML escaping in sitemap generation
1 parent f61b9d5 commit 73b6e81

1 file changed

Lines changed: 14 additions & 6 deletions

File tree

web-server/src/handler/sitemap/generate-xml-sitemap.ts

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@ export interface SiteMapLink {
55
lang: LanguageCode;
66
}
77

8+
function xmlEscape(s: string) {
9+
return s.replace(
10+
/[<>&"']/g,
11+
(c) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;", "'": "&#39;" })[c] as string,
12+
);
13+
}
14+
815
export function generateXmlSitemap(
916
links: Array<{ url: string; lang: LanguageCode }>,
1017
hostname: string,
@@ -16,13 +23,14 @@ export function generateXmlSitemap(
1623
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
1724
xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
1825
${links
19-
.map(
20-
(link) => `
26+
.map((link) => {
27+
const escapedUrl = xmlEscape(link.url);
28+
return `
2129
<url>
22-
<loc>${hostname}${link.url}</loc>
23-
<xhtml:link rel="alternate" hreflang="${link.lang}" href="${hostname}${link.url}" />
24-
</url>`,
25-
)
30+
<loc>${hostname}${escapedUrl}</loc>
31+
<xhtml:link rel="alternate" hreflang="${link.lang}" href="${hostname}${escapedUrl}" />
32+
</url>`;
33+
})
2634
.join("")}
2735
</urlset>`;
2836

0 commit comments

Comments
 (0)