XmlDocumentクラスを使用することで、XMLの作成や読み込みを容易に行えます。
XmlDocument document = new XmlDocument(); XmlDeclaration declaration = document.CreateXmlDeclaration( "1.0", "UTF-8", null ); // XML宣言 XmlElement root = document.CreateElement( "root" ); // ルート要素 document.AppendChild( declaration ); document.AppendChild( root ); XmlElement element = document.CreateElement( "element" ); element.InnerText = "text"; // 要素の内容 element.SetAttribute( "attribute", "256" ); // 属性 root.AppendChild( element ); // ファイルに保存する document.Save( "sample.xml" );
このプログラムは以下のようなファイルを出力します。
<?xml version="1.0" encoding="UTF-8"?> <root> <element attribute="256">text</element> </root>
読み込みはとても簡単で、foreachでループさせるだけですべての要素を取得できます。
XmlDocument document = new XmlDocument(); // ファイルから読み込む document.Load( "sample.xml" ); foreach( XmlElement element in document.DocumentElement ) { string text = element.InnerText; // 要素の内容 string attribute = element.GetAttribute( "attribute" ); // 属性 }