c# - 如何使用 & 对 XML 字符串进行编码

标签 c# xml ampersand

我有一个 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 &amp; am &lt;fine&gt; &amp; dandy</path>
  <title>...</title>
  <description>...</description>
</template>

关于c# - 如何使用 & 对 XML 字符串进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44328650/

相关文章:

java - 如何解决docbuilder SAX异常: unexpected end of document?

batch-file - 批处理文件处理文件夹名称中的符号 (&)

c# - 如何在用户控件中的两个控件之间绘制直线?

java - 读取 xml (windows-1252) 文件时出错

objective-c - XML 解析问题

javascript - 与号 (&amp;) 在 DOM 中未转义生成了 href

PHP echo 自动将 "&"替换为 "&amp;"

c# - Automapper Project从子项访问父项

c# - 正则表达式查找字符串中的重复模式

c# - 为什么 System.Type.GetHashCode 会为所有实例和类型返回相同的值?