如何使用标头获取XML(<?xml version =“1.0”…)?

请考虑以下简单代码,该代码创建XML文档并显示它。

XmlDocument xml = new XmlDocument(); XmlElement root = xml.CreateElement("root"); xml.AppendChild(root); XmlComment comment = xml.CreateComment("Comment"); root.AppendChild(comment); textBox1.Text = xml.OuterXml; 

它按预期显示:

  

但是,它没有显示

  

那我怎么能这样呢?

使用XmlDocument.CreateXmlDeclaration方法创建XML声明:

 XmlNode docNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null); xml.AppendChild(docNode); 

注意:请查看该方法的文档, 尤其encoding参数:对此参数的值有特殊要求。

您需要使用XmlWriter(默认情况下会写入XML声明)。 您应该注意,C#字符串是UTF-16,并且您的XML声明表明该文档是UTF-8编码的。 这种差异可能会导致问题。 这是一个例子,写一个文件,给出你期望的结果:

 XmlDocument xml = new XmlDocument(); XmlElement root = xml.CreateElement("root"); xml.AppendChild(root); XmlComment comment = xml.CreateComment("Comment"); root.AppendChild(comment); XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, ConformanceLevel = ConformanceLevel.Document, OmitXmlDeclaration = false, CloseOutput = true, Indent = true, IndentChars = " ", NewLineHandling = NewLineHandling.Replace }; using ( StreamWriter sw = File.CreateText("output.xml") ) using ( XmlWriter writer = XmlWriter.Create(sw,settings)) { xml.WriteContentTo(writer); writer.Close() ; } string document = File.ReadAllText( "output.xml") ; 
 XmlDeclaration xmldecl; xmldecl = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = xmlDocument.DocumentElement; xmlDocument.InsertBefore(xmldecl, root);