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

#using <System.Xml.dll>
#using <System.dll>
 
#include <string>
#include <vector>
 
using namespace System;
using namespace System::Xml;
using namespace System::Xml::Serialization;
using namespace System::IO;
using namespace System::Collections::Generic;
 
ref class Address;
ref class OrderedItem;
 
[Serializable()]
public ref class Bone
{
public :
	[XmlAttributeAttribute("BoneName")]
	String^	Name;
 
	[XmlElement("BoneID")]
	int		Num;
	int		ParentID;
};
 
[XmlRootAttribute("TestClass", IsNullable=false)]
public ref class TestClass
{
public :
	String^			Message;
 
	[XmlArrayAttribute("Bones")]
	List<Bone^>^ Bones;
 
public :
	TestClass( String^ message, int number )
	{
		Message = message;
 
		Bones = gcnew List<Bone^>( number );
 
		for( int i=0; i<Bones->Capacity; ++i )
		{
			Bone^ bone = gcnew Bone;
 
			bone->Name = "parts";
			bone->Num = i;
			bone->ParentID = i - 1;
 
			Bones->Add( bone );
		}
	}
 
	TestClass()
	{
		Message = String::Empty;
 
		Bones = gcnew List<Bone^>( 0 );
	}
 
	void Print()
	{
		Console::WriteLine( Message );
 
		for each( Bone^ bone in Bones )
		{
			Console::WriteLine( "Name:{0} ID:{1} Parent:{2}",
				bone->Name, bone->Num, bone->ParentID );
		}
	}
};
 
public ref class Program
{
public :
	static void main( array<String^>^ args )
	{
		String^ xmlFileName = args[0];
 
		TestClass^ obj1 = gcnew TestClass( "テストです。", 4 );
 
		SaveFromXmlFile<TestClass>( obj1, xmlFileName );
 
		TestClass^ obj2 = LoadFromXmlFile<TestClass>( xmlFileName );
 
		obj2->Print();
	}
 
public :
	template< typename T >
	static T^ LoadFromXmlFile( String^ path )
	{
		T^ result;
 
		FileStream^ stream = gcnew FileStream( path, FileMode::Open, FileAccess::Read );
 
		XmlSerializer^ serializer = gcnew XmlSerializer( T::typeid );
 
		result = dynamic_cast<T^>( serializer->Deserialize( stream ) );
 
		stream->Close();
 
		return result;
	}
 
	template< typename T >
	static void SaveFromXmlFile( T^ obj, String^ path )
	{
		TextWriter^ stream = gcnew StreamWriter( path );
 
		XmlSerializer^ serializer = gcnew XmlSerializer( T::typeid );
 
		serializer->Serialize( stream, obj );
 
		stream->Close();
	}
};
 
int main()
{
	std::vector<std::string> messages;
 
	messages.push_back( "C:\\test.xml" );
 
	List<String^>^	args = gcnew List<String^>( messages.size() );
 
	for each( std::string message in messages )
	{
		args->Add( gcnew String( message.c_str() ) );
	}
 
	Program::main( args->ToArray() );
 
	return 0;
}
 
最終更新:2008年08月30日 18:41
ツールボックス

下から選んでください:

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