Xmlを使いませう ソースコードcs

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
 
namespace Xml
{
	[Serializable()]
	public class Bone
	{
		[XmlAttributeAttribute("BoneName")]
		public string	Name;
 
		[XmlElement("BoneID")]
		public int		Num;
		public int		ParentID;
	}
 
	[XmlRootAttribute("TestClass", IsNullable=false)]
	public class TestClass
	{
		public string		Message;
 
		[XmlArrayAttribute("Bones")]
		public List<Bone>	Bones;
 
		public TestClass( string message, int number )
		{
			Message = message;
 
			Bones = new List<Bone>( number );
 
			for( int i=0; i<Bones.Capacity; ++i ) {
				Bone bone = new Bone();
 
				bone.Name = "parts";
				bone.Num = i;
				bone.ParentID = i - 1;
 
				Bones.Add( bone );
			}
		}
 
		public TestClass()
			:this( "", 0 )
		{
		}
 
		public void Print()
		{
			Console.WriteLine( Message );
 
			Bones.ForEach(
				delegate( Bone bone )
				{
					Console.WriteLine( "Name:{0} ID:{1} Parent:{2}", bone.Name, bone.Num, bone.ParentID );
				}
			);
		}
	}
 
	class Program
	{
		static void Main(string[] args)
		{
			string xmlFileName = "C:\\test.xml";
 
			TestClass obj1 = new TestClass( "テストです。", 4 );
 
			SaveFromXmlFile<TestClass>( obj1, xmlFileName );
 
			TestClass obj2 = LoadFromXmlFile<TestClass>( xmlFileName );
 
			obj2.Print();
		}
 
		public static T LoadFromXmlFile<T>( string path )
		{
			T result = default(T);
 
			using( FileStream stream = new FileStream( path, FileMode.Open, FileAccess.Read ) )
			{
				XmlSerializer serializer = new XmlSerializer( typeof( T ) );
 
				result = (T)serializer.Deserialize( stream );
			}
 
			return result;
		}
 
		public static void SaveFromXmlFile<T>( T obj ,string path )
		{
			using( TextWriter stream = new StreamWriter( path ) )
			{
				XmlSerializer serializer = new XmlSerializer( typeof( T ) );
 
				serializer.Serialize( stream, obj );
			}
		}
	}
}
最終更新:2008年08月30日 19:01
ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。