Luis Valencia
Luis Valencia

Reputation: 33978

How to generate a sample xml from a class file

I am creating a model in c# and the idea is that later the app I am doing will read data from xml and convert it to object, however I would like to generate a sample xml of that. how can I do that?

my sample c# class is:

 public class SiteDefinition
    {
        public string Name { get; set; }
        public string Version { get; set; }
        public List<MasterPage> MasterPages { get; set; }
        public List<File> Files { get; set; }
        public List<PageLayout> PageLayouts { get; set; }
        public List<Feature> Features { get; set; }
        public List<ContentType> ContentTypes { get; set; }
        public List<StyleSheet> StyleSheets { get; set; }
    }

Upvotes: 0

Views: 660

Answers (2)

Tsukasa
Tsukasa

Reputation: 6552

XML Serialization

Required Namespace

using System.Xml.Serialization;

Read and write class as XML

    public static List<SiteDefinition> Read()
    {
        XmlSerializer reader = new XmlSerializer(typeof(List<SiteDefinition>));
        using (FileStream file = File.OpenRead(Path.Combine(Global.AppRoot, configFileName)))
        {
            return reader.Deserialize(file) as List<SiteDefinition>;
        }
    }

    public static void Write(List<SiteDefinition> settings)
    {
        XmlSerializer writer = new XmlSerializer(typeof(List<SiteDefinition>));
        using (FileStream file = File.Create(Path.Combine(Global.AppRoot, configFileName)))
        {
            writer.Serialize(file, settings);
        }
    }

Upvotes: 1

rwisch45
rwisch45

Reputation: 3702

var instance = new SiteDefinition();
var serializer = new XmlSerializer(typeof(SiteDefinition));

using(var writer = new StreamWriter("C:\\Path\\To\\File.xml"))
{
    serializer.Serialize(writer, instance);
}

And if you want to customize the output (attributes, etc) there are many attributes that you can decorate your class and class members with. Check out this MSDN article for more info

Upvotes: 2

Related Questions