保存xml时如何在c#中使用OmitXmlDeclaration和QuoteChar

保存xml时如何在c#中使用OmitXmlDeclaration和QuoteChar,c#,xml,C#,Xml,我有一些XML文件,并编写了一个c#应用程序来检查缺少的元素、节点并将其保存回去。在我的XMLs中,属性是使用单引号(例如:)。但在保存C#应用程序时,请将这些引号转换为双引号。然后我发现下面的代码使用单引号保存 using (XmlTextWriter tw = new XmlTextWriter(file, null)) { tw.Formatting = Formatting.Indented;

我有一些XML文件,并编写了一个c#应用程序来检查缺少的元素、节点并将其保存回去。在我的XMLs中,属性是使用单引号(例如:
)。但在保存C#应用程序时,请将这些引号转换为双引号。然后我发现下面的代码使用单引号保存

using (XmlTextWriter tw = new XmlTextWriter(file, null))
                    {
                        tw.Formatting = Formatting.Indented;
                        tw.Indentation = 3;
                        tw.IndentChar = ' ';
                        tw.QuoteChar = '\'';                    
                        xmlDoc.Save(tw);                    
                    }
                } 
但它会在那里附加XML声明。然后我找到了删除xml声明的代码

XmlWriterSettings xws = new XmlWriterSettings();
                xws.OmitXmlDeclaration = true;
                xws.Indent = true;
                xws.ConformanceLevel = ConformanceLevel.Fragment;using (XmlWriter xw = XmlWriter.Create(file, xws)){
xmlDoc.Save(xw);
}
然后XML声明再次附加到文本中。我怎么能同时使用它们呢? 我也尝试过下面的代码,但没有使用它

XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
                xws.Indent = true;
                xws.ConformanceLevel = ConformanceLevel.Fragment;                
                using (XmlTextWriter tw = new XmlTextWriter(file, null))
                {
                    tw.Formatting = Formatting.Indented;
                    tw.Indentation = 3;
                    tw.IndentChar = ' ';
                    tw.QuoteChar = '\'';               
                    using (XmlWriter xw = XmlWriter.Create(tw, xws))
                    {
                        xmlDoc.Save(xw);
                    }
                }

XML声明是通过调用
XmlWriter
实现上的
WriteStartDocument
编写的。当您使用推荐的
XmlWriter.Create
XmlWriterSettings
时,可以更改它的行为

但是,推荐的方法不允许您更改引号字符

我能想到的唯一解决方案是创建自己的writer,它源自
XmlTextWriter
。然后您将重写
WriteStartDocument
,以防止写入任何声明:

public class XmlTextWriterWithoutDeclaration : XmlTextWriter
{
    public XmlTextWriterWithoutDeclaration(Stream w, Encoding encoding)
        : base(w, encoding)
    {
    }

    public XmlTextWriterWithoutDeclaration(string filename, Encoding encoding)
        : base(filename, encoding)
    {
    }

    public XmlTextWriterWithoutDeclaration(TextWriter w)
        : base(w)
    {
    }

    public override void WriteStartDocument()
    {        
    }
}
并按您现在的状态使用:

using (var tw = new XmlTextWriterWithoutDeclaration(file, null))
{
    tw.Formatting = Formatting.Indented;
    tw.Indentation = 3;
    tw.IndentChar = ' ';
    tw.QuoteChar = '\'';
    xmlDoc.Save(tw);
}

我是开发新手,您能解释一下XML声明如何不附加在该方法上吗@查尔斯·马格苏尔。声明是通过调用
WriteStartDocument
编写的。在这个子类中,我们重写这个方法,什么也不做。从未调用原始的“基本”实现。