【问题标题】:Linq to XML - Render CDATA as HTMLLinq to XML - 将 CDATA 呈现为 HTML
【发布时间】:2012-11-16 01:34:12
【问题描述】:

我有以下 XML:

<stories>
    <story id="1234">
        <title>This is a title</title>
        <date>1/1/1980</date>
        <article>
            <![CDATA[<p>This is an article.</p>]]>
        </article>
    </story>
</stories>

以及以下 C# 中的 Linq to XML 代码:

@{
    XDocument xmlDoc = XDocument.Load("foo.xml");

    var stories = from story in xmlDoc.Descendants("stories")
                        .Descendants("story")
                        .OrderByDescending(s => (string)s.Attribute("id"))
        select new
        {
            title = story.Element("title").Value,
            date = story.Element("date").Value,
            article = story.Element("article").Value,
        };

    foreach (var story in stories)
    {

        <text><div class="news_item">
            <span class="title">@story.title</span>
            <span class="date">@story.date</span>
            <div class="story">@story.article</div>
        </div></text>

    }
}

渲染后的 HTML 输出到浏览器为:

<div class="news_item">
    <span class="title">This is a title</span>
    <span class="date">1/1/1980</span>
    <div class="story">&lt;p&gt;This is an article.&lt;/p&gt;</div>
</div>

我希望将&lt;p&gt; 标记呈现为浏览器的HTML,而不是编码。我该如何做到这一点?

【问题讨论】:

    标签: c# asp.net razor linq-to-xml


    【解决方案1】:

    Razor 默认对值进行编码。您需要使用 Html.Raw 助手来避免它(Html.Raw() in ASP.NET MVC Razor view)

     <div class="story">@Html.Raw(story.article)</div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      相关资源
      最近更新 更多