How to get XML with header (<?xml version=“1.0”…)?

不羁的心 提交于 2019-11-26 21:09:22

问题


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

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?


回答1:


Create an XML-declaration using XmlDocument.CreateXmlDeclaration Method:

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

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




回答2:


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:

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") ;



回答3:


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

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


来源:https://stackoverflow.com/questions/14839630/how-to-get-xml-with-header-xml-version-1-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!