2017-06-02 27 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