简体   繁体   中英

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; }
    }
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

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);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM