VB.NET, C#, PowerShellを使用しているエンジニアのためのサイト。
基本的な使用方法から開発で役立つTipsまで幅広く取り扱っています。
コメントを追加するには、XmlCommentクラスを使用します。XMLコメントとはで表される文字列です。XmlCommentクラスのCreateCommentメソッドの引数にコメントを作成し、コメントを追加する要素のInsertBeforeメソッドまたはInsertAfterメソッドでコメントを挿入します。
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); // XML宣言を設定する System.Xml.XmlDeclaration xmlDecl = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); //作成したXML宣言をDOMドキュメントに追加します xmlDoc.AppendChild(xmlDecl); //ルート要素の作成 System.Xml.XmlElement rootElement = xmlDoc.CreateElement("personal_data"); //ルート要素をDOMドキュメントに追加する xmlDoc.AppendChild(rootElement); //コメントの作成 System.Xml.XmlComment xmlCmt1 = xmlDoc.CreateComment("コメント1"); //rootElementの後にコメントを挿入します xmlDoc.InsertAfter(xmlCmt1, rootElement); //コメントの作成 System.Xml.XmlComment xmlCmt2 = xmlDoc.CreateComment("コメント2"); //rootElementの前にコメントを挿入します xmlDoc.InsertBefore(xmlCmt2, rootElement); try { //作成したDOMドキュメントをファイルに保存 xmlDoc.Save(@"C:\Work\Test.xml"); } catch ( System.Xml.XmlException ex ) { //XMLによる例外をキャッチ Console.WriteLine(ex.Message); }