You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何将XmlDocument生成的XML声明双引号替换为单引号

问题原因

XmlDocument.CreateXmlDeclaration 方法原生不支持自定义XML声明的引号包裹类型,内部硬编码使用双引号包裹version、encoding属性值,同时会对传入的参数做格式合法性校验:

  • 给参数传入带单引号的值时,版本号参数会变成'1.0',不符合XML规范要求的VersionNum ::= '1.' [0-9]+产生式规则,因此触发参数异常。
  • 该方法没有暴露任何配置项可以修改声明使用的引号类型,无法直接通过调用这个方法生成单引号格式的声明。
可行解决方案

方案1:继续使用XmlDocument,序列化后定向替换声明部分的引号

正常生成符合规范的XML内容,序列化完成后仅对开头的XML声明段做引号替换,不改动其余节点内容的格式:

XmlDocument doc = new XmlDocument();
// 正常传入合法参数生成标准声明,不要额外加单引号
XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(decl);

// 此处添加你的业务节点生成逻辑...
// doc.AppendChild(doc.CreateElement("TestCase"));

// 序列化后替换声明部分的引号
string xmlContent;
using (StringWriter sw = new StringWriter())
{
    doc.Save(sw);
    xmlContent = sw.ToString();
}
// 定位声明段结束位置,仅替换声明段内的双引号
int declEndPos = xmlContent.IndexOf("?>") + 2;
string declSection = xmlContent.Substring(0, declEndPos);
string contentSection = xmlContent.Substring(declEndPos);
string finalXml = declSection.Replace("\"", "'") + contentSection;

// 写入目标文件
File.WriteAllText("test_case_output.xml", finalXml, Encoding.UTF8);

方案2:换用XmlWriter,关闭自动声明后手动写入目标格式声明

使用可控性更高的XmlWriter,关闭默认的XML声明自动生成逻辑,直接写入你需要的单引号格式声明,后续节点正常写入即可:

XmlWriterSettings settings = new XmlWriterSettings
{
    Indent = true, // 按需配置缩进、换行等格式
    Encoding = new UTF8Encoding(false), // 无BOM的UTF8编码,可按需调整
    OmitXmlDeclaration = true // 关闭自动生成的双引号声明
};

using (XmlWriter writer = XmlWriter.Create("test_case_output.xml", settings))
{
    // 直接写入符合目标软件要求的单引号声明
    writer.WriteRaw("<?xml version='1.0' encoding='utf-8'?>");
    
    // 后续正常写入业务节点
    writer.WriteStartElement("TestCases");
    // 你的节点写入逻辑...
    writer.WriteEndElement();
}
注意事项

单引号包裹XML声明的属性值本身符合W3C XML语法规范,只是.NET内置的XML声明生成逻辑默认使用双引号、没有开放修改配置,才会出现这个适配问题。不要尝试通过修改CreateXmlDeclaration入参的方式加单引号,必然触发校验异常。

内容的提问来源于stack exchange,提问作者Anh Hào Trần

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 08:33:11