我有一个 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("&","&") 可以工作,但不是正确的解决方案。
谢谢
最佳答案
最好使用面向 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 & am <fine> & dandy</path>
<title>...</title>
<description>...</description>
</template>
关于c# - 如何使用 & 对 XML 字符串进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44328650/