如何使用标头获取XML(<?xml version ="1.0"...)?

isp*_*iro 20 .net c# xml xmldocument

请考虑以下简单代码,该代码创建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;
Run Code Online (Sandbox Code Playgroud)

它按预期显示:

<root><!--Comment--></root>
Run Code Online (Sandbox Code Playgroud)

但是,它没有显示

<?xml version="1.0" encoding="UTF-8"?>   
Run Code Online (Sandbox Code Playgroud)

那我怎么能这样呢?

Ser*_*nov 31

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

XmlNode docNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
xml.AppendChild(docNode);
Run Code Online (Sandbox Code Playgroud)

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


Nic*_*rey 13

您需要使用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") ;
Run Code Online (Sandbox Code Playgroud)


Asi*_*sif 5

XmlDeclaration xmldecl;
xmldecl = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null);

XmlElement root = xmlDocument.DocumentElement;
xmlDocument.InsertBefore(xmldecl, root);
Run Code Online (Sandbox Code Playgroud)