C# 如何获取带有标题的 XML (<?xml version="1.0"...)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14839630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:11:31  来源:igfitidea点击:

How to get XML with header (<?xml version="1.0"...)?

c#.netxmlxmldocument

提问by ispiro

Consider the following simple code which creates an XML document and displays it.

考虑以下创建 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;

it displays, as expected:

它按预期显示:

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

It doesn't, however, display the

但是,它不显示

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

So how can I get that as well?

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

采纳答案by Sergey Brunov

Create an XML-declaration using XmlDocument.CreateXmlDeclaration Method:

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

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

Note: please take a look at the documentation for the method, especiallyfor encodingparameter: there are special requirements for values of this parameter.

注意:方法请看文档,特别encoding参数:对这个参数的取值有特殊要求。

回答by Nicholas Carey

You need to use an XmlWriter (which writes the XML declaration by default). You should note that that C# strings are UTF-16 and your XML declaration says that the document is UTF-8 encoded. That discrepancy can cause problems. Here's an example, writing to a file that gives the result you expect:

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

回答by Asif

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

XmlElement root = xmlDocument.DocumentElement;
xmlDocument.InsertBefore(xmldecl, root);