xml - ASP.NET MVC 4 和 Razor 2 : View engine no longer supports xml?

标签 xml razor rss asp.net-mvc-4

我们有一个 View (.cshtml),它使用 ASP.NET MVC 3 为 RSS 提要呈现 XML,效果很好。现在我们已经升级到带有 Razor 2 的 ASP.NET MVC 4,它正在生成编译错误,类似于以下内容。

Parser Error

Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Encountered end tag "item" with no matching start tag.  Are your start/end tags properly balanced?

标签适当平衡。

有人有什么想法吗?

更新:我已经将它隔离在@foreach (...) { ... } block 。

@foreach (var item in Model.Items)
{
<item>
    <title>@item.Title</title>
    <link>@item.Link</link>
    <description>@item.Description</description>
    <guid>@item.Guid</guid>
    @if (item.PublishedDateUtc.HasValue)
    {
    <pubDate>@item.PublishedDateUtc.Value.ToString("ddd, dd MMM yyyy HH:mm:ss") GMT</pubDate>
    }  
</item>      
}

我通过使用下面的 @Html.Raw 修复了它。

@foreach (var item in Model.Items)
{
<item>
    <title>@item.Title</title>
    @Html.Raw(string.Format("<link>{0}</link>", item.Link.ToHtmlEncoded()))
    <description>@item.Description</description>
    <guid>@item.Guid</guid>
    @if (item.PublishedDateUtc.HasValue)
    {
    <pubDate>@item.PublishedDateUtc.Value.ToString("ddd, dd MMM yyyy HH:mm:ss") GMT</pubDate>
    }  
</item>      
}

谁有更好的建议?显然,我可以只使用一个类来声明模型并直接从 Controller 返回 XML,但我更感兴趣的是为什么会出现这种行为,以及我可以做些什么来更好地符合 Razor 语法。

最佳答案

当我第一眼看到这个时,我注意到了你的 link标签有一个结束标签而不是自动关闭。 Razor 聪明 足以了解 html 并知道链接标记是如何关闭的。这是另一个可能会破坏的示例,以显示 Razor 如何读取 html。

....
<tbody>
    @if (alternating) {
        <tr class='alternating'>
    } else {
        <tr>
    }

    ....

        </tr>
</tbody>

这将失败,因为它看到一个 </tr>没有开始标签。

始终自闭的标签被 Razor 解释为自闭。所以你的link标签实际上结束于 > . (因为没有 /> 的自关闭标签是有效的 html)所以现在我们遇到了一个没有开始标签的结束标签来证明它是正确的,所以解析器放弃并说它的格式不正确。我必须做一些检查,但我很确定它假设结束 link标签适用于 item标记,因为这会提供适当的平衡,这就是为什么文件的其余部分解析得很好,直到它遇到这个孤独的 item没有开始标签的标签。

它应该足够聪明,知道之前的结束标记不正确。与团队合作可能是个问题。

我没试过,但你应该可以做到这一点

@foreach (var item in Model.Items)
{
<item>
    <title>@item.Title</title>
    @:<link>
        @item.Link
    @:</link>
    <description>@item.Description</description>
    <guid>@item.Guid</guid>
    @if (item.PublishedDateUtc.HasValue)
    {
    <pubDate>@item.PublishedDateUtc.Value.ToString("ddd, dd MMM yyyy HH:mm:ss") GMT</pubDate>
    }  
</item>      
}

关于xml - ASP.NET MVC 4 和 Razor 2 : View engine no longer supports xml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10931376/

相关文章:

github - 设置 Github Commit RSS 源

java - fragment 中绘图应用程序的自定义 View InflateException

java - 如何定制测试报告?

C# Windows 应用商店网格应用 (xaml) 模板

c# - MVC 4 IntelliSense 在 Visual Studio 2010 中的 Razor 中不起作用

asp.net-mvc-3 - 是否有一种更简洁的方法可以在 Razor 中的@variable 后面加上逗号

c# - 在 ASP.NET (C#) 中创建动态 RSS 提要页面 - 我需要做任何额外的事情吗?

c# - LINQ 到 XML : Ignoring of the case of attributes

java - 有没有办法像我们使用 XPath 读取的方式一样编写 XML?

c# - RazorViewEngine.FindPartialView 使用缓存。它有什么作用?