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

2020-01-31 23:20发布

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?

3条回答
别忘想泡老子
2楼-- · 2020-02-01 00:04

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") ;
查看更多
Animai°情兽
3楼-- · 2020-02-01 00:05

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.

查看更多
家丑人穷心不美
4楼-- · 2020-02-01 00:26
XmlDeclaration xmldecl;
xmldecl = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null);

XmlElement root = xmlDocument.DocumentElement;
xmlDocument.InsertBefore(xmldecl, root);
查看更多
登录 后发表回答