28

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"?>   

では、どうすればそれも取得できますか?


XmlDocument.CreateXmlDeclarationメソッドを使用してXML宣言を作成します。

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

注:メソッド、特にパラメーターのドキュメントを参照してencodingください。このパラメーターの値には特別な要件があります。

4

3 に答える 3

39

XmlDocument.CreateXmlDeclaration Methodを使用して XML 宣言を作成します。

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

注: メソッド、特にパラメーターのドキュメントを参照してencodingください。このパラメーターの値には特別な要件があります。

于 2013-02-12T18:52:03.897 に答える
17

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") ;
于 2013-02-12T19:17:47.297 に答える
6
XmlDeclaration xmldecl;
xmldecl = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null);

XmlElement root = xmlDocument.DocumentElement;
xmlDocument.InsertBefore(xmldecl, root);
于 2013-12-18T11:16:14.693 に答える