WCF プロジェクトで Rss20FeedFormatter クラスを使用しているときに、記述要素の内容を<![CDATA[ ]]>
セクションでラップしようとしました。何をしても、description 要素の HTML コンテンツは常にエンコードされ、CDATA セクションは追加されないことがわかりました。Rss20FeedFormatter のソース コードを調べたところ、Summary ノードを構築するときに、以前に指定された設定をすべて消去する新しい TextSyndicationContent インスタンスが基本的に作成されることがわかりました (と思います)。
マイコード
public class CDataSyndicationContent : TextSyndicationContent
{
public CDataSyndicationContent(TextSyndicationContent content)
: base(content)
{
}
protected override void WriteContentsTo(System.Xml.XmlWriter writer)
{
writer.WriteCData(Text);
}
}
... (次のコードは、Summary を CDATA セクションでラップする必要があります)
SyndicationItem item = new SyndicationItem();
item.Title = new TextSyndicationContent(name);
item.Summary = new CDataSyndicationContent(
new TextSyndicationContent(
"<div>This is a test</div>",
TextSyndicationContentKind.Html));
Rss20FeedFormatter コード (私の知る限り、このロジックのため、上記のコードは機能しません)
...
else if (reader.IsStartElement("description", ""))
result.Summary = new TextSyndicationContent(reader.ReadElementString());
...
回避策として、RSS20FeedFormatter を使用して RSS を作成し、RSS に手動でパッチを適用することにしました。例えば:
StringBuilder buffer = new StringBuilder();
XmlTextWriter writer = new XmlTextWriter(new StringWriter(buffer));
feedFormatter.WriteTo(writer ); // feedFormatter = RSS20FeedFormatter
PostProcessOutputBuffer(buffer);
WebOperationContext.Current.OutgoingResponse.ContentType =
"application/xml; charset=utf-8";
return new MemoryStream(Encoding.UTF8.GetBytes(buffer.ToString()));
...
public void PostProcessOutputBuffer(StringBuilder buffer)
{
var xmlDoc = XDocument.Parse(buffer.ToString());
foreach (var element in xmlDoc.Descendants("channel").First()
.Descendants("item")
.Descendants("description"))
{
VerifyCdataHtmlEncoding(buffer, element);
}
foreach (var element in xmlDoc.Descendants("channel").First()
.Descendants("description"))
{
VerifyCdataHtmlEncoding(buffer, element);
}
buffer.Replace(" xmlns:a10=\"http://www.w3.org/2005/Atom\"",
" xmlns:atom=\"http://www.w3.org/2005/Atom\"");
buffer.Replace("a10:", "atom:");
}
private static void VerifyCdataHtmlEncoding(StringBuilder buffer,
XElement element)
{
if (!element.Value.Contains("<") || !element.Value.Contains(">"))
{
return;
}
var cdataValue = string.Format("<{0}><![CDATA[{1}]]></{2}>",
element.Name,
element.Value,
element.Name);
buffer.Replace(element.ToString(), cdataValue);
}
この回避策のアイデアは、次の場所から来ました。MVC ではなく WCF で動作するように調整しました。http://localhost:8732/Design_Time_Addresses/SyndicationServiceLibrary1/Feed1/
これは単なる Rss20FeedFormatter のバグなのか、それとも仕様なのか? また、誰かがより良い解決策を持っているなら、私はそれを聞きたいです!