【C#】输出的XML文件中空标签多换行符
生成的XML文件如下:
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(@"<Config><Version>1.0.0.0</Version><comment></comment></Config>");
//Create an XML declaration.
System.Xml.XmlDeclaration xmldecl;
xmldecl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
//Add the new node to the document.
System.Xml.XmlElement root = doc.DocumentElement;
doc.InsertBefore(xmldecl, root);
string aXMLPath = Environment.CurrentDirectory + "\\TEST.XML";
doc.Save(@aXMLPath);
doc.LoadXml(@"<Config><Version>1.0.0.0</Version><comment></comment></Config>");
//Create an XML declaration.
System.Xml.XmlDeclaration xmldecl;
xmldecl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
//Add the new node to the document.
System.Xml.XmlElement root = doc.DocumentElement;
doc.InsertBefore(xmldecl, root);
string aXMLPath = Environment.CurrentDirectory + "\\TEST.XML";
doc.Save(@aXMLPath);
生成的XML如下
<?xml version="1.0" encoding="utf-8"?>
<Config>
<Version>1.0.0.0</Version>
<comment>
</comment>
</Config>
<Config>
<Version>1.0.0.0</Version>
<comment>
</comment>
</Config>
换成XmlWriter输出即可解决问题
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " ";
settings.Encoding = Encoding.UTF8;
using (XmlWriter xmlWriter = XmlWriter.Create(aXMLPath, settings))
{
doc.Save(xmlWriter);
}
settings.Indent = true;
settings.IndentChars = " ";
settings.Encoding = Encoding.UTF8;
using (XmlWriter xmlWriter = XmlWriter.Create(aXMLPath, settings))
{
doc.Save(xmlWriter);
}
生成的XML如下
<?xml version="1.0" encoding="utf-8"?>
<Config>
<Version>1.0.0.0</Version>
<comment></comment>
</Config>
<Config>
<Version>1.0.0.0</Version>
<comment></comment>
</Config>
本作品采用 知识共享署名-非商业性使用 2.5 中国大陆许可协议进行许可。 |