14-Jun-07 (Created: 14-Jun-07) | More in 'CS-dotnet'

How to stream an Object as XML

How to stream an object as XML to a string


		private static string getXMLAsAString(LoadTenderTrip t)
		{
			XmlSerializer x = new XmlSerializer(typeof(LoadTenderTrip));
			StringWriter w = new StringWriter();
			try
			{
				x.Serialize(w,t);
			}
			finally
			{
				w.Close();
			}
			return w.ToString();
		} 

Controlling root and root field name

[System.Xml.Serialization.XmlRootAttribute(ElementName="MY_XML_CLASS", Namespace="", IsNullable=false)]
Public class MyClass
{
}

Will result in

<MY_XML_CLASS>
</MY_XML_CLASS>

With out "ElementName" it will be

<MyClass>
</MClass>

Controlling array elements

		[System.Xml.Serialization.XmlElementAttribute("LOAD_TENDER_EQUIPMENT")]
		public LoadTenderEquipment[] equipmentArray; 

Without the above attribute you will see

<someroot>
	<equipmentArray>
		<LoadTenderEquipment>
		</LoadTenderEquipment>
	</equipmentArray>
</someroot>

With the above attribute you will see

<someroot>
	<LOAD_TENDER_EQUIPMENT>
	</LOAD_TENDER_EQUIPMENT>
</someroot>

How to write a string to a file

		public static void writeStringToFile(string filename,string msg)
		{
			StreamWriter w = null;
			try
			{
				w = new StreamWriter(filename);
				w.WriteLine(msg);
			}
			finally
			{
				if (w!= null) w.Close();
			}

		}