[英]Why is my XDocument saving the declaration when I don't want it to?
I have the following code: 我有以下代码:
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);
}
}
}
I am trying to get XML to save without the xml declaration, but even though I am nulling out the declaration of the XDocument
, it is still being saved to the final XML. 我试图在没有xml声明的情况下保存XML,但即使我将
XDocument
的声明归零,它仍然被保存到最终的XML中。
This code is outputting: 此代码输出:
<?xml version="1.0" encoding="utf-8"?>
<root>
<subelement1>1</subelement1>
<subelement2>2</subelement2>
</root>
Instead XDocument.Save()
you can use XmlWriter
with XmlWriterSettings.OmitXmlDeclaration
set to true
相反,
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);
}
You can do this using XmlWriter
with a custom XmlWriterSettings
(you'll need a using directive for System.Xml
): 您可以使用
XmlWriter
和自定义XmlWriterSettings
来执行此操作(您需要System.Xml
的using指令):
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
class Program
{
static void Main(string[] args)
{
var xml =
new XElement("root",
new XElement("subelement1", "1"),
new XElement("subelement2", "2"));
var doc = new XDocument(xml);
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true
};
using (var stream = File.Create(@"test.xml"))
{
using (var writer = XmlWriter.Create(stream, settings))
{
doc.Save(writer);
}
}
}
}
That's assuming you want to specify the Stream
- you can also create an XmlWriter
from the filename: 假设您要指定
Stream
- 您还可以从文件名创建XmlWriter
:
using (var writer = XmlWriter.Create("test.xml", settings))
{
doc.Save(writer);
}
(If you don't need the XDocument
for anything else, you can just call Save
on the root element, of course, in the same way.) (如果你不需要其他任何东西的
XDocument
,你可以用同样的方式在根元素上调用Save
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.