Blog

Blogging on programming and life in general.

XML Parsing Error In A MVC Razor View

Posted in: ASP.NET

If you set a Controller's response type to "text/xml", you may encounter an: "XML Parsing Error: XML or text declaration not at start of entity". Your View may look something like this:

@{
    Layout = null;
}

<?xml version="1.0" encoding="utf-8" ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    @if (Model.Any())
    {
        foreach (SitemapNode node in Model)
        {
            <url>
                <loc>@node.Location</loc>
                <lastmod>@node.LastModified</lastmod>
                <changefreq>monthly</changefreq>
            </url>
        }
    }
</urlset>

In this case, I was creating a sitemap for one of my websites. So I created a Controller and View as I normally would do. However, when generating an XML output, you'll have to do something a little different in MVC:

@{
    Layout = null;
}<?xml version="1.0" encoding="utf-8" ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    @if (Model.Any())
    {
        foreach (SitemapNode node in Model)
        {
            <url>
                <loc>@node.Location</loc>
                <lastmod>@node.LastModified</lastmod>
                <changefreq>monthly</changefreq>
            </url>
        }
    }
</urlset>

Can you see what is the difference? You'd be forgiven for not seeing it. But if you look a little closer, you'll see that I pushed up my XML declaration right up next to where I set the Layout block. This is because Razor outputs extra lines within its markup.

So when I left an empty line after my Layout block (as seen my my first code example), this gets rendered as an empty line when you run the page which would not be valid XML.

Update - 28/08/2014

Just found an even better way to get around the same issue from reading Joe Raczkowski blog. All that needs to be done is place the main XML declaration at the top of the page inside the @{} braces:

@{
Layout = null;
Response.ContentType = "text/xml";
Response.Write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
}
blog comments powered by Disqus
;