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

本文关键字:OmitXmlDeclaration QuoteChar 保存 xml | 更新日期: 2023-09-27 18:03:54

我有一些XML文件,我写了一个c#应用程序来检查缺失的元素,节点并将其保存回来。在我的xml中,属性使用单引号(例如:<Person name='Nisala' age='25' >)。但是在保存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);
                    }
                }

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

XML声明是通过在XmlWriter实现上调用WriteStartDocument来编写的。当您使用推荐的XmlWriter.CreateXmlWriterSettings时,可以改变这种行为。

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

我能想到的唯一解决方案是创建自己的作家,从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);
}
相关文章:
  • 没有找到相关文章