从xml文件中删除版本

问题描述:

我使用XmlWriter创建了一种类似于Xml的格式。但是在输出中也有版本信息。从xml文件中删除版本

<?xml version="1.0" encoding="utf-8"?> 

我不需要这个在我的文件中。我怎样才能做到这一点?有什么办法通过代码删除它?

+9

停!请!不要制作“类似XML的格式”。使用真正的XML。如果它是类似于XML的,那么另一个开发人员就会出现,看看它,假定它是XML,然后在尝试将它解析为XML时遇到问题。 (一旦你使用真正的XML,处理指令的使用将不会成为问题,因为在那里给出的值是缺少处理指令时默认的值)。 – Quentin 2009-12-30 13:27:53

+2

这是规范要求的XML声明。你为什么要删除它? (该声明在XML 1.0中是可选的,但在XML 1.1中是必需的) – 2009-12-30 13:28:11

+0

此外,您查找的信息包含在序列化对象时的问题_Omitting XML处理指令中(http://*.com/questions/164585/省略-xml-processing-instruction-when-serializing-an-object) – 2009-12-30 13:28:59

使用ConformanceLevelOmitXmlDeclaration性能。例如:

XmlWriter w; 
w.Settings = new XmlWriterSettings(); 
w.Settings.ConformanceLevel = ConformanceLevel.Fragment; 
w.Settings.OmitXmlDeclaration = true; 
+0

为什么要使用ConformanceLevel它没有设置w.Settings.ConformanceLevel = ConformanceLevel.Fragment;也。什么是ConformanceLevel? – viky 2009-12-31 09:23:01

+1

“碎片”一致性级别意味着你不写整个文档,你正在写一个片段。该文档说,如果'ConformanceLevel'设置为'Document',那么将'OmitXmlDeclaration'设置为'true'不会产生任何影响。 – 2009-12-31 10:10:43

+0

只需要注意,你不需要有'w.Settings.ConformanceLevel = ConformanceLevel.Fragment'这行''如果你也使用'writer.WriteStartDocument();'它会引发错误。有人可能会认为,您不应该以这种方式使用它,但只要您将其保留为'settings.ConformanceLevel = ConformanceLevel.Auto;'即可。 – Ravendarksky 2015-11-23 16:57:24

在创建的XmlWriter,通过你想要使用XmlWriterSettings设置:

XmlWriterSettings settings = new XmlWriterSettings(); 
settings.OmitXmlDeclaration = true; 

writer = XmlWriter.Create(Console.Out, settings); 

XmlWriterSettings具有其他性能,以及(缩进和更多)。