我有以下代码:
class Program
{
static void Main(string[] args)
{
using (var stream = File.Create(@"C:\test.xml"))
{
var xml =
new XElement("root",
new XElement("subelement1", "1"),
new XElement("subelement2", "2"));
var doc = new XDocument(xml);
doc.Declaration = null;
doc.Save(stream);
}
}
}
我正在尝试不使用xml声明而保存XML,但是即使我使
XDocument
的声明为空,它仍被保存到最终XML中。此代码正在输出:
<?xml version="1.0" encoding="utf-8"?>
<root>
<subelement1>1</subelement1>
<subelement2>2</subelement2>
</root>
最佳答案
相反,您可以使用XDocument.Save()
(将XmlWriter
设置为XmlWriterSettings.OmitXmlDeclaration
)来使用true
using System.IO;
using System.Xml;
using System.Xml.Linq;
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Indent = true;
using (var stream = File.Create(@"C:\test.xml"))
using (XmlWriter xw = XmlWriter.Create(stream, xws))
{
var xml = new XElement(
"root",
new XElement("subelement1", "1"),
new XElement("subelement2", "2"));
xml.Save(xw);
}
关于c# - 为什么我不希望XDocument保存声明?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8926784/