Search code examples
c#xmlampersand

How to encode a XML String with &


I have a XML string that sometimes can contain an &. This is the code (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");

I have read about HttpUtility.HtmlEncode, but my problem is that I can't encode the string, since it will be encode again in the last line

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

and I can't change this last line. A String.Replace("&","&") could work but is not a proper solution.

Thanks


Solution

  • Best to build XML with something geared towards XML, such as Xml.Linq

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

    For the correctly escaped

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