Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to XML - Render CDATA as HTML

I have the following 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>

And the following Linq to XML code in C#:

@{
    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>

    }
}

The rendered HTML is output to the browser as:

<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>

I want the <p> tag rendered as HTML to the browser, not encoded. How do I accomplish this?

like image 997
brainbolt Avatar asked Feb 12 '26 19:02

brainbolt


1 Answers

Razor encodes values by default. You need to use Html.Raw helper to avoid it ( Html.Raw() in ASP.NET MVC Razor view )

 <div class="story">@Html.Raw(story.article)</div>
like image 137
Alexei Levenkov Avatar answered Feb 15 '26 17:02

Alexei Levenkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!