2017-06-02 30 views
2

編碼XML字符串我有一個XML字符串,有時可以包含&。這是代碼(C#):如何用&

  var templateDef = String.Format("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><template><path>{0}</path><title>{1}</title><description>{2}</description></template>", templateUrl, templateTitle, templateDescription); 
      return File(System.Text.Encoding.UTF8.GetBytes(templateDef), "application/octet-stream", templateTitle + ".hdtl"); 

我看了一下HttpUtility.HtmlEncode,但我的問題是,我不能編碼字符串,因爲它會在最後一行再次編碼

  return File(System.Text.Encoding.UTF8.GetBytes(templateDef), "application/octet-stream", templateTitle + ".hdtl"); 

我不能改變這最後一行。一個String.Replace(「&」,「&」)可以工作,但不是一個適當的解決方案。

感謝

+1

使用'XElement'而不是通過構建XML字符串替換。 –

回答

3

打造XML的東西對XML面向,如Xml.Linq

var r = new XElement("template", 
      new XElement("path", "i & am <fine> & dandy"), 
      new XElement("title", "..."), 
      new XElement("description", "...")).ToString(); 

對於正確轉義

<template> 
    <path>i &amp; am &lt;fine&gt; &amp; dandy</path> 
    <title>...</title> 
    <description>...</description> 
</template> 
+0

這只是完美的。正是我所需要的,優雅,乾淨,沒有觸及最後一行。謝謝。 – aramos