我有一些XML文件,我已经编写了一个c#应用程序来检查缺少的元素,节点并将其保存回来。在我的XMLs属性中使用单引号(例如:<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);
}
}
答案 0 :(得分:1)
通过在WriteStartDocument
实现上调用XmlWriter
来编写XML声明。当您使用推荐的XmlWriter.Create
和XmlWriterSettings
时,可以更改此行为。
但是,建议的方法不允许您更改引号字符。
我能想到的唯一解决方案是创建自己的作家,源自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);
}