如何使用&编码XML字符串

时间:2017-06-02 12:11:29

标签: c# xml ampersand

我有一个XML字符串,有时可以包含&amp ;.这是代码(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(&#34;&amp;&#34;,&#34;&amp;&#34;)可以工作,但不是一个合适的解决方案。

由于

1 个答案:

答案 0 :(得分: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>