C# 如何获取带有标题的XML(<;?XML版本=";1.0";…)?

C# 如何获取带有标题的XML(<;?XML版本=";1.0";…)?,c#,.net,xml,xmldocument,C#,.net,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; 如预期的那样,它会显示: <

考虑以下创建并显示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;
如预期的那样,它会显示:

<root><!--Comment--></root>

但是,它不会显示

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


那么,我怎样才能得到它呢?

使用以下方法创建XML声明:


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

您需要使用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") ;

谢谢我以为那是自动的。请注意,预期的“Utf-8”与字符串编码不匹配(请参阅+1 Nicholas Carey答案)。@AlexeiLevenkov谢谢。但是我正在
OuterXml
ing它并使用它。还是我遗漏了什么,甚至在那时也有问题?@ispiro
string s=”“
在某种程度上是一个谎言(C#/.Net中
字符串的编码不是UTF8)。取决于代码/用法的其他部分,这可能是问题,也可能不是问题(即,如果将其保存为UTF16失败,则会遇到麻烦)。谢谢
InsertBefore
看起来很有用。如何使用此代码设置列宽?我可以在ASP.NET MVC中使用此代码吗?
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);