VB.NET, C#, PowerShellを使用しているエンジニアのためのサイト。
基本的な使用方法から開発で役立つTipsまで幅広く取り扱っています。
要素の値を設定するにはXmlDocumentクラスのCreateTextNodeメソッドで値を作成し、指定要素のAppendChildメソッドに引数として渡すことで設定します。
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"); //子要素の作成 System.Xml.XmlElement childElement = xmlDoc.CreateElement("zip"); //子要素のテキスト内容を作成 System.Xml.XmlText childValue; childValue = xmlDoc.CreateTextNode("123-4567"); //子要素の値を設定する childElement.AppendChild(childValue); //子要素をルート要素に追加する rootElement.AppendChild(childElement); //ルート要素をDOMドキュメントに追加する xmlDoc.AppendChild(rootElement); try { //作成したDOMドキュメントをファイルに保存 xmlDoc.Save(@"C:\Work\Test.xml"); } catch ( System.Xml.XmlException ex ) { //XMLによる例外をキャッチ Console.WriteLine(ex.Message); }