Skip to content

Commit 32895f9

Browse files
committed
Changed how encoding is handled
Previously, to ensure that the XML delaration was being written, a `StringWriter` was used. `StringWriter` _always_ outputs `UTF-16`, however, regardless of what the `XDeclaration` is set to. That's a problem, as Sitemap.org _mandates_ `UTF-8` and e.g. Google will reject a sitemap that uses `UTF-16`. To mitigate this, the `StringWriter` is remoted and, instead, a simple approach is taken: simply declare a standalone `XElement` and serialize it to a string alongside the `XDocument`. (Note: Calling `ToString()` on an `XDocument` won't include the `XDeclaration`, which is why the `StringWriter` had previously been used.)
1 parent c9319c2 commit 32895f9

1 file changed

Lines changed: 3 additions & 7 deletions

File tree

OnTopic.AspNetCore.Mvc/Controllers/SitemapController.cs

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -107,16 +107,13 @@ public virtual ActionResult Index() {
107107
/*------------------------------------------------------------------------------------------------------------------------
108108
| Establish sitemap
109109
\-----------------------------------------------------------------------------------------------------------------------*/
110-
var sitemap = GenerateSitemap(rootTopic);
111-
var sitemapFile = new StringBuilder();
112-
using (var writer = new StringWriter(sitemapFile)) {
113-
sitemap.Save(writer);
114-
}
110+
var declaration = new XDeclaration("1.0", "utf-8", "no");
111+
var sitemap = GenerateSitemap(rootTopic);
115112

116113
/*------------------------------------------------------------------------------------------------------------------------
117114
| Return the homepage view
118115
\-----------------------------------------------------------------------------------------------------------------------*/
119-
return Content(sitemapFile.ToString(), "text/xml");
116+
return Content(declaration.ToString() + sitemap.ToString(), "text/xml");
120117

121118
}
122119

@@ -129,7 +126,6 @@ public virtual ActionResult Index() {
129126
/// <returns>The site's homepage view.</returns>
130127
public virtual XDocument GenerateSitemap(Topic rootTopic) =>
131128
new XDocument(
132-
new XDeclaration("1.0", "utf-8", String.Empty),
133129
new XElement(_sitemapNamespace + "urlset",
134130
from topic in rootTopic?.Children
135131
select AddTopic(topic)

0 commit comments

Comments
 (0)