Generate XML file from C# class

A

Arjen

Hello,

Like my question below... sorry, I hope this is a better explanation of my
question.
What I want is to generate is a XML file from my existing C# class.
I want to use this XML file for XML serialization.



How can I generate a well formed XML file from my C# code?




Thanks!
 
J

Jax

If all you want to do is serialize an instance of class
into an XML file here is what your looking for:

//at the top
using System.Xml.Serialization;
using System.Xml;
using System.IO;

//a sample class

public class MyClass
{
public string something;
public MyClass()
{
something = "";
}
}

//in code

MyClass myClass = new MyClass();
myClass.something = "someInformation";
string path = @"c:\SomeFolder\myXmlFile.xml";
TextWriter tr = new StreamWriter(path);
XmlSerializer sr = new XmlSerializer(typeof(MyClass));
sr.Serialize(tr,m);
tr.Close();

Obviously this can be acheived in the same way with more
complex classes with more datatypes etc.
One word of warning, if your thinking of serializing a
weakly typed collection (e.g an ArrayList) you have to
specify what types of instances of classes are going to be
contained within.
This is done through XML attributes above the class, i'm
not sure of the exact syntax but i'm sure it's on the msdn
site and visual studio help (if your running that).

Hope that helps in some way.

jax
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top